Created
July 29, 2017 13:08
-
-
Save xenogenesi/dbf93de51deecc95c01db6887b15afa1 to your computer and use it in GitHub Desktop.
Yii2 actionMigrateUp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function actionMigrateUp() | |
{ | |
// https://github.com/samdark/yii2-webshell | |
// https://github.com/samdark/yii2-webshell/issues/3 | |
// https://github.com/tebazil/yii2-console-runner/blob/master/src/ConsoleCommandRunner.php | |
// https://stackoverflow.com/a/28820239/2498790 | |
/* // if exec() is available | |
ob_start(); | |
try { | |
$output = Array(); | |
exec(__DIR__ . '/../../yii migrate/up', $output); | |
echo implode("\n", $output); | |
} catch(\Exception $ex) { | |
echo $ex->getMessage(); | |
} | |
return htmlentities(ob_get_clean(), null, Yii::$app->charset); | |
*/ | |
$oldApp = \Yii::$app; | |
//Define, if you want to capture output | |
defined('STDIN') or define('STDIN', fopen('php://input', 'r')); | |
defined('STDOUT') or define('STDOUT', fopen('php://output', 'w')); | |
//Create new console app, if you do not run it from root namespace you should use '\yii\console\Application' | |
$runner = new \yii\console\Application([ | |
'id' => 'auto-migrate', | |
'controllerNamespace' => 'console\controllers', //for migrate command it should not matter but for other cases you must specify otherwise applocation cannot find your controllers | |
'basePath' => dirname(__DIR__ . '/../../console/config'), //This must point to your console config directory, when i run this in frontend sitecontroller i must add '/../../console/config', | |
'components' => [ 'db' => $oldApp->db ], | |
]); | |
ob_start(); | |
try { | |
$runner->runAction('migrate/up'); | |
} catch(\Exception $ex) { | |
echo $ex->getMessage(); | |
} | |
\Yii::$app = $oldApp; | |
return htmlentities(ob_get_clean(), null, Yii::$app->charset); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment