在命令中重用代码,即创建 BaseCommand 以重用"use"语句、参数和公共变量



我在Laravel 5.8中编写了许多导入命令,这些命令都采用相同的参数并导入一部分数据。例如,我有一个ImportUsersCommand.phpImportFilesCommand.phpImportNotesCommand.php,它们都采用location_id参数(还有大量的命令,但我试图保持这个例子简单(。这些脚本都连接到特定于该位置的外部MS SQL Server数据库,然后运行一些代码将数据导入MySQL数据库。

我注意到我正在重用很多相同的来,我想将其重构为类似BaseImportCommand.php的东西。

示例命令 - 导入用户命令.php(我目前拥有的(

<?php
namespace AppConsoleCommandsImports;
use IlluminateConsoleCommand;
// Models
use AppModelsLocation;
use AppModelsFiles;
use AppModelsNotes;
use AppModelsUser;
// ... and the list continues with many more models!
use DB;
use Hash;
use Schema;
use CarbonCarbon;
// ... 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 AppConsoleCommandsImports;
use AppConsoleCommandsImportsBaseImportCommand;
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文件中设置所有常用语句。 您的命令需要设置的任何通用代码都可以在BaseImportCommand内部的__construct()中,您已经拥有,但它只是空的。

最新更新