php 如何从命令行调用控制器?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 如何从命令行调用控制器?相关的知识,希望对你有一定的参考价值。

namespace App\Services;

class FooService
{
    public function performFoo ()
    {
        // Do what you need
    }
}

Then inject it in the controller actions you want and use it :

namespace App\Http\Controllers;

// ...
use App\Services\FooService;

class SomeController extends Controller
{
    public function SomeAction (FooService $foo_service)
    {
        $foo_service->performFoo();
    }
}
Then create a command and inject the service to use it :

namespace App\Console\Commands;

// ...
use App\Services\FooService;

class Foo extends Command
{
    protected $signature = 'foo';

    protected $description = 'Perform foo';

    private $foo_service;

    public function __construct(FooService $foo_service)
    {
        $this->foo_service = $foo_service;
    }

    public function handle ()
    {
        $this->foo_service->performFoo();
    }
}
Then in app/Console/Kernel.php set the scheduling :

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    protected $commands = [
        \App\Console\Commands\Inspire::class,
        \App\Console\Commands\Foo::class,
    ];

    protected function schedule(Schedule $schedule)
    {
            $schedule->command('inspire')->hourly();
        $schedule->command('foo')->hourly();
    }
}

以上是关于php 如何从命令行调用控制器?的主要内容,如果未能解决你的问题,请参考以下文章

如何从需要SUDO的php调用shell脚本?

如何从需要 SUDO 的 php 调用 shell 脚本?

在 psql 命令行上传递数组参数

为啥这个带有 shell_exec 调用的 PHP 脚本从 Windows 10 的命令行运行,而不是浏览器/本地主机?

如何从命令行执行 PHP 代码?

如何将变量作为标准输入从 PHP 传递到命令行