我有一个控制台命令来做一个消费者时间,我需要知道如何在YII中的Web应用程序操作中调用(执行)它。
class MyCommand extends CConsoleCommand{
public function actionIndex(){
$model = new Product();
$model->title = 'my product';
...
$model->save();
.
.
.
}
}
我想执行这段代码。
试试这个:
Yii::import('application.commands.*');
$command = new MyCommand("test", "test");
$command->run(null);
必须设置值为“test”的2个参数但没有影响,使用控制台时它们用于--help选项。
/**
* Constructor.
* @param string $name name of the command
* @param CConsoleCommandRunner $runner the command runner
*/
public function __construct($name,$runner)
{
$this->_name=$name;
$this->_runner=$runner;
$this->attachBehaviors($this->behaviors());
}
https://github.com/yiisoft/yii/blob/master/framework/console/CConsoleCommand.php#L65
试试这个
Yii::import('application.commands.*');
$command = new GearmanCommand('start', Yii::app()->commandRunner);
$command->run(array('start', '--daemonize', '--initd'));
其中array('start',' - damonmon',' - initd')是一个动作和动作参数
我遇到了同样的问题 - 我需要从控制器内部和命令中调用动作
我说同样的问题,因为它实际上是相同的 - 你需要从控制台调用的动作,并从控制器调用它。
If you need to call an action(command) as a part of controller action, then i think you need to modify this solution a little
。或者我的解决方案对您来说足够了吗?
所以这是我的解决方案:
首先在http://www.yiichina.net/doc/guide/1.1/en/basics.controller#action中创建动作
class NotifyUnsharedItemsAction extends CAction
{
public function run()
{
echo "ok";
}
}
然后在控制器动作中照常加载:
class TestController extends Controller
{
public function actions() {
return array(
'notifyUnsharedItems'=>'application.controllers.actions.NotifyUnsharedItemsAction',
);
}
并在命令中我以这种方式运行动作:
class NotifyUnsharedItemsCommand extends CConsoleCommand
{
public function run($args)
{
$action = Yii::createComponent('application.controllers.actions.NotifyUnsharedItemsAction',$this,'notify');
$action->run();
}
}
接受我们在linux服务器上,对于Yii 1.1现实生活中的例子是:
$run = '/usr/bin/php ' . Yii::getPathOfAlias('root').'/yiic' [command]
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $run, '/dev/null', '/dev/null'));
这将在后台运行Yii控制台命令。
Yii是PHP - >你可以使用http://php.net/manual/en/function.exec.php指定的标准php结构和页面底部附近的相关方法,具体取决于你想要实现的目标。
另外,cebe
对gist的另一个非常干净的解决方案:
<?php
// ...
$runner=new CConsoleCommandRunner();
$runner->commands=array(
'commandName' => array(
'class' => 'application.commands.myCommand',
),
);
ob_start();
$runner->run(array(
'yiic',
'idbrights',
));
echo nl2br(htmlentities(ob_get_clean(), null, Yii::app()->charset));
Yii::app()->end();
通常,在这些情况下您应该做的是重构。将“常用”代码移出MyCommand并将其放入位于components
文件夹中的类中。现在,您可以将任何头放在“常用”代码之上,而无需更改功能。例如:
保护/组件/ Mywork.php:
<?php
class Mywork
{
public function doWork()
{
$model = new Product();
$model->title = 'my product';
...
$model->save();
...
}
}
保护/控制器/ MyworkController.php:
<?php
class MyworkController
{
public function actionDowork()
{
$mywork = new Mywork;
...
}
}
保护/命令/ MyworkCommand.php:
<?php
class MyworkCommand extends CConsoleCommand
{
public function run($args)
{
$mywork = new Mywork;
...
}
}
这种方法使测试更容易,因为您可以将Mywork作为您正在使用的视图之外的单个单元进行测试。