【问题标题】:Get response of custom artisan command in controller在控制器中获取自定义工匠命令的响应
【发布时间】:2020-12-02 06:35:02
【问题描述】:

我创建了自定义工匠命令并试图得到它的响应。 这里是自定义工匠命令的句柄方法。

 /**
 * Execute the console command.
 *
 * @return string
 */
public function handle()
{
    return 'Hello world';
}

从控制器调用命令

$result = Artisan::output('app:custom-command');
dd($result); // 0
dd(Artisan::output()); // ''

在控制器中期待“Hello world”。

请注意我想要响应而不是输出

即不是$this->info('test.');的输出

【问题讨论】:

  • 命令只能返回整数返回状态。这是我所知道的大多数操作系统的限制,所以我希望 laravel 将任何返回值强制转换为字符串。

标签: laravel laravel-6


【解决方案1】:

命令不返回特定变量,它们返回退出代码。 如果你从命令中得到“hello world”;

命令:

$this->info('Hello World');

控制器:

Artisan::call('app:custom-command');
return Artisan::output();

【讨论】:

  • 感谢您的回答,但我知道这一点,并且如前所述,是期望响应和输出的问题。
  • hmm 没有办法返回命令的值。只有退出代码返回
【解决方案2】:

首先,请在此处查看这些答案: Get response from Artisan call

只是为了给你一个见解,在这里你可以做一件小事:

  1. 可以通过引用Command类的构造函数来传递变量

举个例子:

// File => UserController
$commandInstance = new DemoCommand($output);
$commandInstance->hanlde(); // Calling the related method manually

// Then in the DemoCommand Class @constructur method
public function __construct(&$output){
 $this->output = $output;
}

// File => DemoCommand @handle Method
$result = ['a', 'b' ]; // ... 
$commandInstance->setOutput($result);
  1. 您也可以使用 session、Redis 将数据保存在内存中并从您需要的相关类中读取或将输出存储到文件或数据库中...

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2017-08-03
    • 2021-12-14
    • 2019-09-19
    • 2021-12-31
    • 2018-02-21
    相关资源
    最近更新 更多