通过命令行调用Laravel控制器

53
在Kohana框架中,我可以使用命令行调用控制器:
php5 index.php --uri=controller/method/var1/var2

在Laravel 5中是否可能通过cli调用我想要的控制器?如果是,那么如何实现?

6个回答

66

目前还没有这种方法(不确定将来是否会有)。但是你可以创建自己的Artisan命令来实现这一点。使用以下命令创建一个名为CallRoute的命令:

php artisan make:console CallRoute

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

php artisan make:command CallRoute

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

<?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数组中,注册该命令:

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

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

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

请注意,此命令将返回响应,就像它将发送到浏览器一样,这意味着它包含输出顶部的HTTP标头。


3
对于 Laravel 4,使用 php artisan command:make CallRoute 创建命令。内核实际上就是路由器,因此该命令需要包含 $this->info(app()[\Illuminate\Routing\Router::class]->handle($request)); 代码。将该命令添加到 Artisan 中可在 app/start/artisan.php 文件中使用 Artisan::add(new CallRoute); 实现。 - dave1010
这个解决方案似乎在Laravel 5.4中停止工作了,并出现了以下错误:exception 'Illuminate\Contracts\Container\BindingResolutionException' with message 'Target [\Illuminate\Contracts\Http\Kernel] is not instantiable.' - Thomas Cheng
1
找到了解决方法。不要使用:app()['Illuminate\Contracts\Http\Kernel'],而是使用:app()->make(\Illuminate\Contracts\Http\Kernel::class)。 - Thomas Cheng

60

我正在使用 Laravel 5.0,并且我正在使用以下代码触发控制器:

$ php artisan tinker
$ $controller = app()->make('App\Http\Controllers\MyController');
$ app()->call([$controller, 'myMethodName'], []);

app()->call()中的最后一个[]可以包含参数,例如[user_id] => 10等。


有没有一种非交互式调用的方法? - linuxbandit
php artisan tinker打开一个shell,我需要在其中输入另外两行代码。但是我希望能够直接执行它们,因为我要将它们放入脚本中。目前我只是将第2行和第3行合并成一行,并将其导入到第一行中 - 想知道是否有更好的解决方案。 - linuxbandit
嗯,我用这个进行测试,所以我只是逐行编写,发送第三行后查看响应。 - Broshi
@Broshi - 这里的 Tinkerapp() 是什么? - 151291
不必写整个 app()->call([$controller, 'myMethodName'], []); 调用方法,可以使用更简单的方式调用 $controller->someFunction()。 - Rizki Hadiaturrasyid
显示剩余4条评论

22
对于 Laravel 5.4: php artisan make:command CallRoute 然后在 app/Console/Commands/CallRoute.php 中:
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Http\Request;

class CallRoute extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'route:call {uri}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'php artsian route:call /route';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $request = Request::create($this->argument('uri'), 'GET');
        $this->info(app()->make(\Illuminate\Contracts\Http\Kernel::class)->handle($request));
    }

}

然后在 app/Console/Kernel.php 文件中:

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

像这样调用:php artisan route:call /path


2
这也是 Laravel 5.5 的一个非常优雅的解决方案。 - Martin Joiner
也适用于 Laravel 5.6。 - andromeda
不错的解决方案。记得在 config/tinker.php 配置文件中的 $commands 下添加 'App\Console\Commands\CallRoute',这样你就可以从 tinker 中运行此命令了。 - Soulriser
1
在 Lumen 中,这会生成:目标 [Illuminate\Contracts\Http\Kernel] 无法实例化 - Alex
这个答案比预期的更好。 - Abbas

6

您也可以用以下方法完成此操作。首先,使用以下命令创建:

php artisan command:commandName

现在在命令的handle中,调用控制器并触发方法。 例如:

public function handle(){
 $controller = new ControllerName(); // make sure to import the controller
 $controller->controllerMethod();
}

这将确实发挥作用。希望对你有所帮助。

依赖注入无法正常工作


以这种方式调用方法时,DI被忽略。 - alberto-bottarini
DI - 依赖注入。对吗? - Koushik Das
在“command”命名空间中没有定义任何命令。 - be3

6

Laravel 5.7

使用 tinker

 // URL: http://xxx.test/calendar?filter[id]=1&anotherparam=2
 $cc = app()->make('App\Http\Controllers\CalendarController');
 app()->call([$cc, 'getCalendarV2'], ['filter[id]'=>1, 'anotherparam' => '2']);

1

升级到 Laravel 8 版本。

第一步:在终端中输入命令
php artisan tinker

第二步:

$instante = new MyController(null);

如果参数是模型的一个实例,则传递模型类的名称。
例如:
$instante = new MyController(new MyModelHere());

按回车键

最后,在此处调用方法$instante->myMethod()

参见: 输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接