highliuk / wordpress-command

使用 Symfony Console 而不是 WP-CLI,轻松定义 WordPress 中的自定义命令

1.2.1 2024-06-20 15:32 UTC

This package is auto-updated.

Last update: 2024-09-20 15:59:03 UTC


README

一种在 WordPress 中使用 Symfony Console(而不是 WP-CLI)定义自定义命令的简单方法。

安装

使用 composer 安装包

composer require highliuk/wordpress-command

用法

首先,通过扩展 Command 类创建您的自定义命令

use Highliuk\WordPressCommand\Command;

/**
 * Greets the blog with its name.
 */
class HelloBlog extends Command
{
    protected function handle(): void
    {
        $name = get_bloginfo('name');

        $this->line("Hello, $name!");
    }
}

然后,在您的 WordPress 代码中注册您的命令

use Highliuk\WordPressCommand\Application;

$app = Application::getInstance();
$app->add(new HelloBlog());

现在您可以运行您的自定义命令

vendor/bin/console hello:blog
# Hello, My Blog!

您可以使用所有 Symfony Console 功能,例如选项和参数。有关更多信息,请参阅 Symfony Console 文档

功能

自动推断名称和描述

默认情况下,命令名称从类名称推断。例如,HelloBlog 命令将可用为 hello:blog。同样,命令描述从类 docblock 推断。如果您想自定义命令名称和描述,您可以在 configure 方法中使用 setNamesetDescription 方法(请参阅 自定义),或者您可以使用简写属性

use Highliuk\WordPressCommand\Command;

class HelloBlog extends Command
{
    protected $name = 'greet:blog';
    protected $description = 'Greets the blog with its name.';

    protected function handle(): void
    {
        $name = get_bloginfo('name');

        $this->line("Hello, $name!");
    }
}

自定义

您可以通过重写 configure 方法来自定义命令(类似于 Symfony Console 命令)

use Highliuk\WordPressCommand\Command;

class HelloBlog extends Command
{
    protected function configure(): void
    {
        $this->setName('greet:blog');
    }

    protected function handle(): void
    {
        $name = get_bloginfo('name');

        $this->line("Hello, $name!");
    }
}

参数和选项绑定

您可以从您的 handle 方法访问参数和选项

use Highliuk\WordPressCommand\Command;
use Symfony\Component\Console\Input\InputArgument;

class GreetUser extends Command
{
    protected function configure(): void
    {
        $this
            ->addArgument('user', InputArgument::REQUIRED, 'The user to greet')
            ->addOption('uppercase', 'u', 'Whether to uppercase the user name');
    }

    protected function handle(string $user, bool $uppercase): void
    {
        if ($uppercase) {
            $user = strtoupper($user);
        }

        $this->line("Hello, $user!");
    }
}
vendor/bin/console greet:user john -u
# Hello, JOHN!

许可证

本项目采用 MIT 许可证 - 有关详细信息,请参阅 LICENSE 文件。