我正在开发一个用于学习建议的客户 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.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;
}
}
用途:
php bin/console.php example
输出:
Hello console