I have a console command to do a consumer time, AND I need to know how to call (execute) it in a web application action in YII.
class MyCommand extends CConsoleCommand{
public function actionIndex(){
$model = new Product();
$model->title = 'my product';
...
$model->save();
.
.
.
}
}
I want to execute this code.
Typically what you should do in these situations is refactor. Move the "common" code out of the MyCommand and place it into a class located in the
components
folder. Now you can place any head on top of the "common" code without altering your functionality. For example:protected/components/Mywork.php:
protected/controller/MyworkController.php:
protected/commands/MyworkCommand.php:
This approach makes testing easier too as you can test Mywork as a single unit outside of the view you are using.
Accepting that we are on linux server, for Yii 1.1 real life example would be:
This will run Yii console command in the background.
try this:
Also, another very clean solution from
cebe
on gist:I had same problem - i need to call action from inside controller and from command
I said same problem because it actually same - you have action which you need to call from console, and call it from controller too.
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
. Or is my solution is enough for you?So here is my solution:
first create action as said in http://www.yiichina.net/doc/guide/1.1/en/basics.controller#action
then in controller action is loaded as usuall:
and in command i run action in such way:
Yii is PHP -> you can use the standard php constructs specified at http://php.net/manual/en/function.exec.php and the related methods near the bottom of the page, depending on what exactly you want to achieve.