Console commands
Not everything on a site happens on a browser request: mailing, cleaning old records or an import are started from a terminal or on a schedule. Console commands are written for that. A command in Yii is the same kind of controller with actions, only it is called through the yii file.
Where a command lives
Commands are stored in the commands folder, and the namespace is app\commands. The project already has an example, commands/HelloController.php. Create your own file by hand:
// commands/PostController.php
namespace app\commands;
use app\models\Post;
use yii\console\Controller;
use yii\console\ExitCode;
class PostController extends Controller
{
public function actionCount(): int
{
$count = Post::find()->count();
$this->stdout("Posts in the database: $count\n");
return ExitCode::OK;
}
}php yii post/countThe command prints the number of posts. The route is built the same way as on the site: a controller and an action. stdout() prints text to the terminal, and ExitCode::OK tells the system that the command finished successfully.
Arguments
Method arguments are the words after the command name:
public function actionPublish($id): int
{
$post = Post::findOne($id);
if ($post === null) {
$this->stderr("Post $id not found\n");
return ExitCode::DATAERR;
}
$post->status = 1;
$post->save();
$this->stdout("Post $id published\n");
return ExitCode::OK;
}php yii post/publish 5The number 5 goes into the $id argument. stderr() prints an error message, and a code other than ExitCode::OK reports a failure.
Options
An option is an optional setting of the form --name=value. It is declared as a class property and listed in the options() method:
public $days = 30;
public function options($actionID): array
{
return array_merge(parent::options($actionID), ['days']);
}
public function actionClean(): int
{
$deleted = Post::deleteAll([
'and',
['status' => 0],
['<', 'created_at', time() - $this->days * 86400],
]);
$this->stdout("Drafts deleted: $deleted\n");
return ExitCode::OK;
}php yii post/clean --days=90The command deletes drafts older than 90 days; without the option, older than 30.
Help
| Command | What it shows |
|---|---|
php yii | The list of all commands |
php yii help post | The actions of the post controller |
php yii help post/clean | The arguments and options of an action |
The description of a command in the help is taken from the comment before the method.
Running on a schedule
On a server commands are started by the cron scheduler. A line in its table:
0 3 * * * php /var/www/blog/yii post/clean --days=90Every night at three o'clock the server runs the cleanup. The path to the yii file is given in full.
Common mistake
The console reads config/console.php, not config/web.php. It has no request, session or current user: accessing Yii::$app->user or Yii::$app->session in a command ends with an error. Pass everything needed as arguments.