首页 > 解决方案 > 为我自己的自定义 php 框架创建我的自定义工匠

问题描述

我正在开发一个用于学习建议的自定义 PHP 框架,现在我需要为我的框架创建自定义 cli,并且我想在不同的作曲家包中制作它,以便单独使用和更新。

问题是:

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

例如:

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

$bin/console hello-world

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

或者

创建一个自定义文件,例如名为 command 的工匠,并像这样使用它

commander hello-world

标签: phplaravelsymfony

解决方案


您可以使用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

推荐阅读