mardi 6 février 2018

call a model from a command class in Laravel 5, and pass the command class itself

I have a laravel 5.5 artisan command working, so of course I can use methods like $this->info() and $this->arguments() etc.. it looks like this:

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();    
    }
}

Of course, I would like do the actual work in the Model, not the command, using the command like a controller. Here's the model class so far:

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! -----';
    }
}

To the point, how do I pass the Command object to the Model so that I can use $this->command->arguments() or the other Command features inside the model?

P.S. I'd be very grateful to know if there's a native "Laravel way" to do this better than passing the entire $this to a constructor.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire