V
V
Vladimir2018-10-28 12:09:45
Yii
Vladimir, 2018-10-28 12:09:45

How to redirect output using Yii runAction?

Good day! I have an action "actionAddSuperAdmin" in it, I create a user in one database and, based on his data, create his database, so to speak, and if it is successfully created, then I apply migrations to it, here is a piece of code:

try {
    $sql = Yii::$app->db->createCommand('CREATE DATABASE ' . $db_name)->execute();
    if ($sql) {
        \Yii::$app->runAction('user/migrate', ['db_name' => $db_name]);
    }
} catch (Exception $e) {
    return $this->asJson(['success' => false, 'errors' => json_encode($e)]);
}

return $this->asJson($response);

Here is the method itself, which is called after the successful creation of the database:
public function actionMigrate($db_name)
{
    // https://github.com/yiisoft/yii2/issues/1764#issuecomment-42436905
    $oldApp = \Yii::$app;
    new \yii\console\Application([
        'id' => 'Command runner',
        'basePath' => '@console',
        'components' => [
            'db' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'mysql:host=localhost;dbname=' . $db_name . '',
                'username' => 'root',
                'password' => '',
                'charset' => 'utf8',
            ],
        ],
    ]);
    \Yii::$app->runAction('migrate/up',
        ['migrationPath' => '@console/migrations', 'interactive' => false]);
    \Yii::$app = $oldApp;
}

But after its execution, the response from the server is not what I need:
> create table {{%user}} ... done (time: 0.366s) > create index idx-user-subdomain on user (subdomain) ... done (time: 0.114s) ... и так все таблицы

And in the end:
Exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in E:\OSPanel\domains\order.loc\vendor\yiisoft\yii2\db\Migration.php on line 577.' in E:\OSPanel\domains\order.loc\vendor\yiisoft\yii2\web\Response.php:366 Stack trace: #0 E:\OSPanel\domains\order.loc\vendor\yiisoft\yii2\web\Response.php(339): yii\web\Response->sendHeaders() #1 E:\OSPanel\domains\order.loc\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Response->send() #2 E:\OSPanel\domains\order.loc\frontend\web\index.php(38): yii\base\Application->run() #3 {main}

What should I do to avoid this output, but the one that goes further in the code (that is, "return $this->asJson($response);")?
Thanks in advance for your replies!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2018-10-28
@MasterGerold

Output Buffering

ob_start();

// Вызов вашего метода
 
// если необходимо сохраняем всё что есть в буфере в переменную
$content = ob_get_contents();
 
// отключаем и очищаем буфер
ob_end_clean();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question