首页 > 解决方案 > 在命令中重用代码,即创建一个 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变量分配给另一个可以用于每个导入命令的文件?

任何帮助将非常感激!

标签: phplaravellaravel-5extends

解决方案


你几乎拥有它。

您的自定义命令扩展了您的通用 BaseImportCommand,后者扩展了 Laravel 的命令。

您可以在文件中设置所有常用语句BaseImportCommand。您的命令设置所需的任何通用代码都可以在您已经拥有的__construct()内部BaseImportCommand,但它只是空的。


推荐阅读