You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 11中不依赖Console/Kernel.php通过Action注册命令

在Laravel 11中通过Action注册全局Artisan命令

你当前将Action添加到config/tinker.php的commands配置中,这只会让该命令在Tinker环境内可用,并非全局的Artisan命令。以下是Laravel 11中通过Action注册全局Artisan命令的正确步骤:

1. 确保安装依赖包

AsAction和AsCommand trait来自lorisleiva/laravel-actions扩展包,若未安装,先执行:

composer require lorisleiva/laravel-actions

2. 完善Action命令类

你的Action类结构已基本正确,需确保完整引入依赖类:

<?php

namespace App\Actions;

use Lorisleiva\Actions\Concerns\AsAction;
use Lorisleiva\Actions\Concerns\AsCommand;
use Illuminate\Console\Command;

class SitemapGenerateAction
{
    use AsAction, AsCommand;

    public string $commandSignature = 'sitemap:generate';
    public string $commandDescription = 'Generate the sitemap';

    protected array $sitemapData;

    public function handle(): void
    {
        // 编写生成站点地图的核心逻辑
    }

    public function asCommand(Command $command): void
    {
        // 命令行交互与输出逻辑
        $this->handle();
        $command->info('Sitemap generated successfully!');
    }

    public function asController(): array
    {
        // 作为控制器的响应逻辑
        $this->handle();
        return ['status' => 'success'];
    }
}

3. 注册全局Artisan命令

Laravel 11移除了Console/Kernel.php,有两种方式注册命令:

方式一:通过bootstrap/app.php注册

在应用配置文件中直接指定要注册的命令类:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // 中间件配置
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // 异常配置
    })
    ->commands([
        \App\Actions\SitemapGenerateAction::class,
    ])
    ->create();

方式二:通过routes/console.php注册

在控制台路由文件中添加命令注册代码:

use App\Actions\SitemapGenerateAction;

Artisan::command(SitemapGenerateAction::class);

注:若使用的laravel-actions版本支持自动发现,只要Action类位于App\Actions目录并使用了AsCommand trait,会自动注册为全局命令,无需手动配置。

验证与使用

执行以下命令查看所有可用Artisan命令,确认sitemap:generate存在:

php artisan list

若已注册成功,直接运行命令生成站点地图:

php artisan sitemap:generate

内容的提问来源于stack exchange,提问作者Ivan Kachula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:02:08