10

编辑:找出我哪里出错并在最后放置了一个答案

我正在尝试创建一个 Laravel 命令,我可以看到它与 Laravel 3 中的“任务”发生了很大变化。但是我似乎无法让它运行。这些是我采取的步骤:

php artisan 命令:make 导入

退货

命令创建成功

然后创建命令目录中的文件,我稍作修改以返回“Hello World”,如下所示:

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class Import extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'command:import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        return 'Hello World';
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('example', InputArgument::REQUIRED, 'An example argument.'),
        );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
        );
    }

}

但是,当我尝试像这样运行命令时:

php工匠导入

我收到以下错误:

[InvalidArgumentException] 命令“导入”未定义。

我已经尝试过使用和不使用大写字母以及将其命名为“ImportCommand”,因为文档将其命令命名为“FooCommand”但没有运气。

非常感激任何的帮助。

4

4 回答 4

17

其实是想通了。在文档的下方,它指出您必须使用以下方法在“app/start/artisan.php”中注册您的命令:

Artisan::add(new import);

您在命令类中给出的名称也很重要,因为您需要使用它来调用它。所以我实际上应该这样称呼它:

php artisan command:import

最后一件事。fire() 返回的内容并不重要,要返回字符串,您必须回显它们。

于 2013-06-18T14:58:42.633 回答
7

尝试这个。

protected function getArguments()
{
    return [];
}

protected function getOptions()
{
    return [];
} 

也添加这个/app/start/artisan.php

Artisan::add(new ParseCommand);

然后在根目录上运行命令

./artisan command:import; 
于 2014-02-04T06:31:43.587 回答
2

在较新的 Laravel 版本中,没有import命令。你只需要做以下两件事:

  1. 在以下位置注册您的命令app/start/artisan.php

    Artisan::add(new Import);
    
  2. 在 Artisan 中运行命令:

    php artisan command:name Import
    
于 2014-05-12T15:47:20.723 回答
0

there's a mis-understanding on Artisan commands because of the used wording.

In your case you choose : 'command:import' as a name of one of your 'Import' commands.

Think about it as an object, with methods.

If "Import" has many commands:

you can use as command name > protected $name = 'import:csv';

another command would be > protected $name = 'import:txt';

and > protected $name = 'import:contacts';

so your commands with "Import" nature are better organised.

and when you request , you see your commands organised as a single entity.

If not,

and you have only a single command then give your command a single clear name. protected $name = 'import';

于 2014-02-25T08:52:59.923 回答