建立命令

使用 make:command 这个 Artisan 命令可以产生一个新的命令类 :

php artisan make:command PurchasePodcast

新产生的类会被放在 app/Commands 目录中,命令默认包含了两个方法:构造器和 handle 。当然,handle 方法执行命令时,你可以使用构造器传入相关的对象到这个命令中。例如:

class PurchasePodcast extends Command implements SelfHandling {

    protected $user, $podcast;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(User $user, Podcast $podcast)
    {
        $this->user = $user;
        $this->podcast = $podcast;
    }

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        // Handle the logic to purchase the podcast...

        event(new PodcastWasPurchased($this->user, $this->podcast));
    }

}

handle 方法也可以使用类型提示依赖,并且通过 服务容器 机制自动进行依赖注入。例如:

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle(BillingGateway $billing)
    {
        // Handle the logic to purchase the podcast...
    }
文章导航