arrow_back
Back

Yii2 console actions: bootstrapping an app and running actions

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Sometimes you need to bootstrap a Yii application manually and invoke one of its console actions from a standalone script.

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';

$config = require __DIR__ . '/config/console.php';

$application = new yii\console\Application($config);

$application->runAction('app/process-spreadsheet');

Passing parameters to the action:

$application->runAction('app/process-spreadsheet', ['test']);

Running actions in parallel threads

With the pthreads extension each thread bootstraps its own application instance, because the framework state is not shared between threads:

class SpreadsheetThread extends Thread
{
    private $spreadsheet_id;

    public function __construct($spreadsheet_id)
    {
        $this->spreadsheet_id = $spreadsheet_id;
    }

    public function run()
    {
        require __DIR__ . '/vendor/autoload.php';
        require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';

        $config = require __DIR__ . '/config/console.php';

        $application = new yii\console\Application($config);

        $application->runAction('app/process-spreadsheet', [$this->spreadsheet_id]);
    }
}

$thread_1 = new SpreadsheetThread(1);
$thread_2 = new SpreadsheetThread(2);

$thread_1->start();
$thread_2->start();

pthreads requires a ZTS build of PHP — see the PHP notes on multithreading for the installation details and alternatives (PCNTL, daemons).

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 MongoDB extension: queries with yii2-mongodb

arrow_forward