Mastering Yii
上QQ阅读APP看书,第一时间看更新

Configuration and usage

The basic structure of Yii2 console applications is very similar to the structure used in web applications. In Yii2, console commands that extend from yii\console\Controller are nearly identical to yii\web\Controller.

Entry script

Before moving on to the configuration files themselves, let's take a look at the console entry script, which is part of the file called yii. This entry script serves as the bootstrapper for all our console commands, and in general, they can be run by calling this:

$ ./yii

This command will output all the currently available commands for the system. Like the web/index.php entry script, though, it isn't aware of its environment yet. We can change this by replacing yii with the following code block:

#!/usr/bin/env php
<?php
/**
 * Yii console bootstrap file.
 */

// Define our application_env variable as provided by nginx/apache
if (!defined('APPLICATION_ENV'))
{
 if (getenv('APPLICATION_ENV') != false)
 define('APPLICATION_ENV', getenv('APPLICATION_ENV'));
 else 
 define('APPLICATION_ENV', 'prod');
}

$env = require(__DIR__ . '/config/env.php');

defined('YII_DEBUG') or define('YII_DEBUG', $env['debug']);

// fcgi doesn't have STDIN and STDOUT defined by default
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));

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

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

$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);

Note

This script is intended for Linux-like environments. Yii2 also provides a yii.bat file that can be run on Windows. If you're following along on a Windows computer, ensure that you change yii.bat in addition to the yii file.

With our entry script files configured, we're ready to take a look at our application configuration files.

Tip

You may also notice that in the web/ folder, there is a separate entry script called index-test.php. This script is used by Codeception, a testing framework that is used to run unit, functional, and acceptance tests in Yii2. We'll cover how to configure and use this entry script and Codeception in Chapter 10, Testing with Codeception.

Configuration

In Yii2, the console configuration file is located at config/console.php and is nearly identical to our web configuration file:

<?php

Yii::setAlias('@tests', dirname(__DIR__) . '/tests');

return [
    'id' => 'basic-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'app\commands',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => require(__DIR__ . '/db.php'),
    ],
    'params' => require(__DIR__ . '/params.php'),
];

Like our web configuration file, we can include our database and parameters' configuration files using the environment-aware configurations we wrote in Chapter 1, Composer, Configuration, Classes, and Path Aliases. In fact, the only major difference between our web and console configuration is the explicit declaration of our console command namespace and the explicit declaration of the @test alias, which defines where our test files will be located.

Tip

Thanks to Yii's extremely flexible structure, we can reorganize our bootstrap and entry script files to be in many different physical locations on our file system. Because of this flexibility, the console configuration file expects us to declare the @test alias explicitly so that we can run our console tests.

Setting the console environment

Following the same convention we set up for our web application, we now need to instruct our console to pass the APPLICATION_ENV variable to our console application. From the command line, we can easily change the environment by exporting a variable:

export APPLICATION_ENV="dev"

Tip

If we want to make this change permanent for the server we are working on, we can store this variable in our ~/.bash_profile file, or we can store it globally for all users at /etc/profile. By adding this command to either of these files, the next time we log in to our shell, this variable will automatically be exported. Note that if you're using Windows, you'll need to export this variable to your %path% variable.

Go ahead and give it a try! Log out and log in to your shell again and run the following:

echo $APPLICATION_ENV

If your computer is configured correctly, you should see the environment outputted to your screen.

dev

Running console commands

With our console application now configured, we can easily run our console commands by running the following command:

$ ./yii

Tip

On Windows, this command is yii.bat.

If you are familiar with Yii1, this command has now replaced the /yiic command.

Without any arguments, this is the same as running /yii help and will output the help menu, which lists all the built-in console commands for our application:

$ ./yii

Yii provides additional help information for each of the default commands. For example, if we want to see what subcommands exist for the cache command, we can run the following:

$ ./yii help cache

In general, we can reduce the usage of the Yii console to the following pattern:

$ ./yii <route> [--option1=value1 --option2=value2 ... \
argument1 argument2 ...]

Here, <route> refers to the specific controller and action that we want to run. For example, if we wanted to flush the entire cache for our application from the console, we could run the following command:

$ ./yii cache/flush-all

This is the output we receive:

The following cache components were processed:
 * cache (yii\caching\FileCache)

The ./yii command also enables you to use alternative console configuration files from the same command:

$ ./yii <route> --appconfig=path/to/config.php

Without having to change anything in our code, we can simply instruct Yii to use an alternate configuration file, which can contain anything, ranging from something as simple as a reference to another database or cache to something more complex such as an entirely different controller namespace. This option is especially useful when creating applications that have both a frontend and a backend that may contain different caches or database components.