如何在yii2中从web运行控制台命令

问题描述 投票:9回答:6

我用console/controllersSuggestionController中创建了一个控制台命令。

如果我运行像php yii suggestions这样的命令,它的工作。

我想知道如何从web执行控制台命令,没有yii2的任何扩展。

php shell cron console yii2
6个回答
5
投票

它可以做得更简单

$oldApp = \Yii::$app;
new \yii\console\Application([
    'id' => 'Command runner',
    'basePath' => '@app',
    'components' => [
        'db' => $oldApp->db,
    ],
);
\Yii::$app->runAction('migrate/up', ['migrationPath' => '@yii/rbac/migrations/', 'interactive' => false]);
\Yii:$app = $oldApp;

Github LINK


2
投票

这是我发现并使用前一段时间运行yii控制台控制器/操作的方式(我用它来从web运行迁移)。

在您的Web控制器操作中:

// default console commands outputs to STDOUT
// so this needs to be declared for wep app
if (! defined('STDOUT')) {
    define('STDOUT', fopen('/tmp/stdout', 'w'));
}

$consoleController = new \yii\console\controllers\SuggestionController;
$consoleController->runAction('your action eg. index');

/**
* open the STDOUT output file for reading
*
* @var $message collects the resulting messages of the migrate command to be displayed in a view
*/
$handle = fopen('/tmp/stdout', 'r');
$message = '';
while (($buffer = fgets($handle, 4096)) !== false) {
$message .= $buffer . "\n";
}
fclose($handle);

return $message;

1
投票

你可以exec()你的命令'''php yii suggestions'''但这可能会导致webserver用户的权限问题。

更好的方法是使用ConsoleRunner扩展,例如yii2-console-runner yii2-console-runner-extensionpopen()做一份更复杂,更安全的工作控制工作。

执行exec()之类时,请始终注意代码注入!


1
投票

从Yii2 - 2.0.11.2高级应用程序 - 这是有效的

首先让我们确保控制器和名称空间正确。在这种情况下,前端应用程序访问控制台应用程序导入方法()

在console \ controllers \ FhirController中

enter image description here

将别名设置为在console \ config \ main.php中可用[可选]

enter image description here

'aliases' => [
    '@common' => dirname(__DIR__),
    '@frontend' =>  dirname(dirname(__DIR__)) . '/frontend',
    '@backend' =>  dirname(dirname(__DIR__)) . '/backend',
    '@console' =>  dirname(dirname(__DIR__)) . '/console',
],

最后从前端视图,调用这样的调用:在这种情况下,调用控制器路由fhir然后方法import()

$consoleController = new console\controllers\FhirController('fhir', Yii::$app); 
$consoleController->runAction('import');

1
投票

在我正在检修的网站上,我需要一个后台任务,可以通过动作切换,这要求我也可以使用ps找到它的pid。经过大量的谷歌搜索和几乎同样多的咒骂,我拼凑了解决方案。

# First change to (already-calculated) correct dir:
chdir($strPath);

# Now execute with nohup, directed to dev/null, and crucially with & at end, to run async:
$output = shell_exec("nohup php yii <console controller>/<action> > /dev/null &");

是的,我知道应该非常谨慎地使用shell_exec,谢谢。


0
投票

我认为这是最简单的解决方案:

$controller = new SuggestionController(Yii::$app->controller->id, Yii::$app);
$controller->actionSuggestions();
© www.soinside.com 2019 - 2024. All rights reserved.