通过命令行调用laravel控制器 [英] Call laravel controller via command line

查看:114
本文介绍了通过命令行调用laravel控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在kohana框架中,我可以使用命令行通过命令行调用控制器

In kohana framework I can call controller via command line using

php5 index.php --uri=controller/method/var1/var2

是否可以通过cli在Laravel 5中调用我想要的控制器?如果是,该怎么做?

Is it possible to call controller I want in Laravel 5 via cli? If yes, how to do this?

推荐答案

到目前为止,还没有办法(不确定是否会出现).但是,您可以创建自己的 Artisan Command 来做到这一点.使用以下命令创建命令CallRoute:

There is no way so far (not sure if there will ever be). However you can create your own Artisan Command that can do that. Create a command CallRoute using this:

php artisan make:console CallRoute

对于Laravel 5.3或更高版本,您需要使用make:command代替:

For Laravel 5.3 or greater you need to use make:command instead:

php artisan make:command CallRoute

这将在app/Console/Commands/CallRoute.php中生成命令类.该类的内容应如下所示:

This will generate a command class in app/Console/Commands/CallRoute.php. The contents of that class should look like this:

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Http\Request;

class CallRoute extends Command {

    protected $name = 'route:call';
    protected $description = 'Call route from CLI';

    public function __construct()
    {
        parent::__construct();
    }

    public function fire()
    {
        $request = Request::create($this->option('uri'), 'GET');
        $this->info(app()['Illuminate\Contracts\Http\Kernel']->handle($request));
    }

    protected function getOptions()
    {
        return [
            ['uri', null, InputOption::VALUE_REQUIRED, 'The path of the route to be called', null],
        ];
    }

}

然后您需要通过将命令添加到app/Console/Kernel.php中的$commands数组中来注册命令:

You then need to register the command by adding it to the $commands array in app/Console/Kernel.php:

protected $commands = [
    ...,
    'App\Console\Commands\CallRoute',
];

您现在可以使用以下命令调用任何路由:

You can now call any route by using this command:

php artisan route:call --uri=/route/path/with/param

请记住,此命令将返回发送到浏览器的响应,这意味着它在输出的顶部包含HTTP标头.

Mind you, this command will return a response as it would be sent to the browser, that means it includes the HTTP headers at the top of the output.

这篇关于通过命令行调用laravel控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆