Run Yiic directly from your app without a shell

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

How to run Yiic from your Yii application without shelling out to the console

Introduction

Sometimes it would be nice if we could run yiic from an action, for example a migrate database button in our admin panel. Or because you are on a host which doesn't have shell access. Or maybe you are not allowed run popen or exec.

Whatever reason, it turns out to be easy enough to add that feature to your application. :)

The following code runs 'yiic migrate --interactive=0' and echos the output.

Run yiic migrate in an action
Code
private function runMigrationTool() {
    $commandPath = Yii::app()->getBasePath() . DIRECTORY_SEPARATOR . 'commands';
    $runner = new CConsoleCommandRunner();
    $runner->addCommands($commandPath);
    $commandPath = Yii::getFrameworkPath() . DIRECTORY_SEPARATOR . 'cli' . DIRECTORY_SEPARATOR . 'commands';
    $runner->addCommands($commandPath);
    $args = array('yiic', 'migrate', '--interactive=0');
    ob_start();
    $runner->run($args);
    echo htmlentities(ob_get_clean(), null, Yii::app()->charset);
}
How to use

You can call it from a controller action like this:

actionMigrate() {
    $this->runMigrationTool();
}

It's up to you to tailer it to your needs. Maybe let it return json or a string instead of echoing directly, so that you can hook it up with an ajax action to get realtime output.

Conclusion

You can run any command you want, as long as it's available to yiic. It doesn't use console configuration at all.

This code is based on the webshell extension, so credit should go there.

13 0
20 followers
Viewed: 49 413 times
Version: Unknown (update)
Category: How-tos
Written by: jacmoe
Last updated by: jacmoe
Created on: Aug 27, 2011
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles