gpt4 book ai didi

php - 通过命令行调用 laravel Controller

转载 作者:IT王子 更新时间:2023-10-29 01:01:26 25 4
gpt4 key购买 nike

在 kohana 框架中,我可以通过命令行调用 Controller

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

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

最佳答案

目前还没有办法(不确定是否会有)。但是您可以创建自己的Artisan Command可以做到这一点。使用以下命令创建命令 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',
];

您现在可以调用任何route通过使用此命令:

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

请注意,此命令将在发送到浏览器时返回响应,这意味着它在输出顶部包含 HTTP header 。

关于php - 通过命令行调用 laravel Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28866821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com