Yii2 - 从另一个控制台命令中调用 Yii 控制台命令? [英] Yii2 - Call a Yii console command from within another console command?
问题描述
我创建了两个不同的 Yii2 控制台命令/控制器.
I have created two different Yii2 console commands/controllers.
调用它们的示例是
# yii user/create-account
和
# yii webserver/update-config
在 user/create-account 运行后,我想调用 webserver/update-config - 是否可以通过代码在 Yii 中执行此操作?或者我必须使用 exec()/system() 来外部调用第二个 yii php 脚本(我不想这样做).
After user/create-account has run I want to call webserver/update-config - is it possible doing this from within Yii by code? Or do I have to use exec()/system() to externally call the second yii php script (I would prefer not to).
任何帮助/见解将不胜感激!
Any help/insight would be appreciated!
推荐答案
经过一番考虑,我选择从另一个控制器中调用一个控制器的方式是使用控制器的 runAction 方法(这也是 Yii 推荐的方式)开发人员).
After some consideration the way I chose to call one controller from within another was by using the runAction method of the controller (which is also the recommended way by the Yii developers).
控制台应用程序示例:
\Yii::$app->runAction('webserver/update-config');
也可以使用数组作为第二个参数来传递参数.
It is also possible to hand over params by using an array in as second parameter.
简单参数示例:
\Yii::$app->runAction('webserver/update-config', ['oneValue', 'anotherValue'];
这里有一个命名参数的例子:
Here an example for named parameters:
\Yii::$app->runAction('webserver/update-config', [
'servertype' => 'oneSetting',
'serverdir' => 'anotherSettingValue'
]);
请注意,这使被调用的控制器成为调用代码的一部分.所以如果被调用的控制器由于某种原因失败,整个程序就会失败.良好的错误处理是必须的.在被调用的控制器中,您可以使用 return 设置要返回的错误代码.
Please note that this makes the called controller a part of the calling code. So if the called controller fails for some reason the whole program fails. Good error handling is a must. In the called controller you can set the error code to give back by using return.
示例:
调用代码行:
$iExitCode = \Yii::$app->runAction('webserver/update-config', ['oneValue', 'anotherValue'];
被调用的控制器:
<?php
namespace app\commands;
use yii\console\Controller;
/**
* Webserver related functions
*/
class WebserverController extends Controller {
public function actionUpdateConfig($oneValue, $anotherValue) {
// Code that does something
if ($success) return 0;
else return 1;
}
}
?>
这篇关于Yii2 - 从另一个控制台命令中调用 Yii 控制台命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!