php - 在命令中重用代码,即创建一个 BaseCommand 以重用“使用”语句、参数和公共变量
问题描述
我在 Laravel 5.8 中编写了许多导入命令,它们都采用相同的参数并导入一部分数据。例如,我有一个ImportUsersCommand.php
, ImportFilesCommand.php
, 并且ImportNotesCommand.php
它们都带有一个location_id
参数(还有很多命令,但我试图让这个例子保持简单)。这些脚本都连接到特定于该位置的外部 MS SQL Server 数据库,然后运行一些代码将数据导入 MySQL 数据库。
我注意到我重用了很多相同的来,我想将它重构为类似BaseImportCommand.php
.
示例命令 - ImportUsersCommand.php(我目前拥有的)
<?php
namespace App\Console\Commands\Imports;
use Illuminate\Console\Command;
// Models
use App\Models\Location;
use App\Models\Files;
use App\Models\Notes;
use App\Models\User;
// ... and the list continues with many more models!
use DB;
use Hash;
use Schema;
use Carbon\Carbon;
// ... and the list continues with many more!
class ImportUsers extends Command
{
protected $signature = 'import:users {location_id}';
protected $description = 'Import users from another data source';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->info($this->description);
ini_set('memory_limit', '4000M');
$location = Location::findOrFail($this->argument('location_id'));
Config::set("database.connections.chirotouch", [
'driver' => env('SQLSERVER_DB_CONNECTION'),
'host' => env('SQLSERVER_DB_HOST'),
'port' => env('SQLSERVER_DB_PORT'),
'database' => 'location_'.$location->id,
'username' => env('SQLSERVER_DB_USERNAME'),
'password' => env('SQLSERVER_DB_PASSWORD'),
]);
// ... and the code continues just for setting up the command...
// Only after about 100 lines of code do we actually get to the
// specifics of what this particular command does.
foreach ($location->users as $user) {
// Do what I need to do
}
}
}
我希望 ImportUsersCommand.php 看起来像什么
<?php
namespace App\Console\Commands\Imports;
use App\Console\Commands\Imports\BaseImportCommand;
class ImportUsers extends BaseImportCommand
{
protected $signature = 'import:users {location_id}';
protected $description = 'Import users from another data source';
public function __construct()
{
parent::__construct();
}
public function handle()
{
foreach ($location->users as $user) {
// Do what I need to do
}
}
}
但我在起草我的BaseImportCommand.php
. 如何提取use
语句、连接到外部数据库、$this-info()
语句、配置语句(例如增加内存限制)以及将$location
变量分配给另一个可以用于每个导入命令的文件?
任何帮助将非常感激!
解决方案
你几乎拥有它。
您的自定义命令扩展了您的通用 BaseImportCommand,后者扩展了 Laravel 的命令。
您可以在文件中设置所有常用语句BaseImportCommand
。您的命令设置所需的任何通用代码都可以在您已经拥有的__construct()
内部BaseImportCommand
,但它只是空的。
推荐阅读
- c# - AxWMPLib.AxWindowsMediaPlayer 对 WMV 文件表现出奇怪的行为
- ios - Swift UDP 连接问题
- google-sheets - 谷歌表格:如何从一个范围创建一个数组,在每一行中添加一个具有恒定文字值的列?
- c# - Flowlayoutpanel用鼠标滚动许多控件
- c++ - 平台之间的不同 typeid
- cakephp - 当表名包含“公司”时,下拉菜单不填充“名称”字段
- python - 将一个数字除以熊猫中列的所有值
- html - 在悬停时更改 Material UI Autocomplete 的边框颜色
- hadoop - 从在线数据集中将数据加载到 Hive 表后获取 NULL 值
- jquery - 跨域请求被阻止:同源策略不允许读取位于 .../Signature.asmx/SendIdDocuments 的远程资源