从Laravel 5中的命令类调用模型,并传递命令类本身

时间:2018-02-06 11:45:29

标签: laravel-5 artisan

我有一个laravel 5.5 artisan命令,所以当然我可以使用像$this->info()$this->arguments()等方法。它看起来像这样:

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Compasspointmedia\Julietmenu\Model\Menu;

class MenuManagementCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'julietmenu:menu 
    {action=list}';

    protected $description = 'Manages menu elements per the Juliet CMS specification';

    public function __construct() {
        parent::__construct();
        //trying to make this command methods available in Menu
        $this->menu = new Menu($this);
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // this works just fine
        $this->info('Calling ' . $this->argument('action'));

        $action = $this->argument('action');
        $this->menu->action();    
    }
}

当然,我想使用像控制器这样的命令在Model而不是命令中进行实际工作。到目前为止,这是模型类:

namespace Compasspointmedia\Julietmenu\Model;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model {
    //
    public function __construct($command){
        $this->command = $command;
        // this says the `arguments` method is present:
        print_r(get_class_methods($this->command));

        // but, it does not work!
        // error: "Call to a member function getArguments() on null"
        $this->arguments = $this->command->arguments();
    }

    public function node(){
        echo '--- it works! -----';
    }
}

到目前为止,如何将Command对象传递给模型,以便我可以在模型中使用$this->command->arguments()或其他命令功能?

P.S。我非常感谢知道是否有本土的Laravel方式"这样做比将整个$this传递给构造函数更好。

0 个答案:

没有答案