【问题标题】:Create my custom like artisan for my own custom php framework为我自己的自定义 php 框架创建我的自定义工匠
【发布时间】:2019-08-18 10:55:59
【问题描述】:

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

问题是:

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

例如:

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

$bin/console hello-world

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

创建一个自定义文件,例如名为指挥官的工匠并使用它

commander hello-world

【问题讨论】:

  • Laravel 的 artisan 命令只是一个简单的可执行 php 脚本,没有 .php 扩展名。 github.com/laravel/laravel/blob/master/artisan
  • 好的,我知道,但是我如何在我的框架中使用 cli 包命令
  • 这是一个很宽泛的问题,而且非常有说服力,我的建议是查看 laravel 源代码以了解如何操作,当您遇到特定的编程问题时,请在此处寻求帮助。
  • 答案是:你不能。如果您执行php artisan list,那么在您运行它的当前目录中必须有一个名为artisan 的文件。您当然可以创建一个仅充当另一个可执行文件的包装器的文件(并将输入重定向到vendor/bin/console),但您需要在项目目录中创建一个文件。

标签: php laravel symfony


【解决方案1】:

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

ExampleCommand.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多