php - 像 artisan 一样为我自己的自定义 php 框架创建自定义

标签 php laravel symfony

我正在开发一个用于学习建议的客户 PHP 框架, 现在我需要为我的框架创建自定义 cli,并且我想将其放在不同的 Composer 包中以便单独使用和更新。

问题是:

如何在我的框架中使用分离的 cli 及其命令,就像在框架中使用其内部命令一样?!或者换句话说,我如何在 Laravel 中为我的 cli 包创建像 artisan 这样的文件?

例如:

在 cli Composer 包中,这是运行命令的方法

$bin/console hello-world

我希望能够在需要 cli 包后在我的框架中使用此命令

或者

像 artisan 一样创建一个名为 Commander 的自定义文件并像这样使用它

commander hello-world

最佳答案

您可以使用symfony/console

安装:

composer require symfony/console

创建文件:bin/console

#!/usr/bin/env php
<?php

// load all commands here from an external php file
$commands  = [
    \App\Console\ExampleCommand::class,
];

$application = new \Symfony\Component\Console\Application();

foreach ($commands as $class) {
    if (!class_exists($class)) {
        throw new RuntimeException(sprintf('Class %s does not exist', $class));
    }
    $command = new $class();
    $application->add($command);
}

$application->run();

示例命令.php

<?php
namespace App\Console;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Command.
 */
class ExampleCommand extends AbstractCommand
{
    /**
     * Configure.
     */
    protected function configure()
    {
        parent::configure();
        $this->setName('example');
        $this->setDescription('A sample command');
    }

    /**
     * Execute command.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int integer 0 on success, or an error code
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Hello console');

        return 0;
    }
}

用法:

bin/console example

输出:

Hello console

关于php - 像 artisan 一样为我自己的自定义 php 框架创建自定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543865/

相关文章:

php - 在单个查询中搜索逗号分隔的 MySQL 列中的多个值

php - 基于条件的方法链

php - laravel的评论功能,错在哪里?

php - Symfony3 在类型文件中创建没有实体的表单

php - 将网站服务嵌入另一个网站的最佳方式

php - Laravel Scheduler 不运行命令,但可以手动运行

php - 有没有办法在 Laravel Dusk 中断言当前 URL 值?

php - EasyAdmin 3 - 具有嵌套形式的 CRUD

facebook - Symfony HWIOAuthBundle 从 facebook 获取用户事件和喜欢

php - 使用 BINARY 查询 ZF2 模型