Sometimes, an application requires some background tasks, such as regenerating a site map or refreshing statistics. A common way to implement this is by using cron jobs. When using Yii, there is a way to use a command to run as a job.
In this recipe, we will see how to implement both. For our recipe, we will implement writing the current timestamp into a t
imestamp.txt
file under the protected directory.
Create a new yii2-app-basic
application by using the Composer, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-startinstallation.html.
Let us try to run appcommandsHelloController::actionIndex
as a shell command:
<?php namespace appcommands; use yiiconsoleController; /** * This command echoes the first argument that you have entered. */ class HelloController extends Controller { /** * This command echoes what you have entered as the message. * @param string $message the message to be echoed. */ public function actionIndex($message = 'hello world') { echo $message . " "; } }
php yii
Alternatively, you also can call the following and ensure that the shell works:
./yii
hello
:./yii help hello
DESCRIPTION This command echoes what you have entered as the message. USAGE yii hello [message] [...options...] - message: string (defaults to 'hello world') the message to be echoed.
./yii hello
Alternatively, run the concrete index
action:
./yii hello/index
Hello world
./yii hello 'Bond, James Bond'
You also can create your own console controllers. For example, create a commands/CronController.php
file with the sample code:
<?php namespace appcommands; use yiiconsoleController; use yiihelpersConsole; use Yii; /** * Console crontab actions */ class CronController extends Controller { /** * Regenerates timestamp */ public function actionTimestamp() { file_put_contents(Yii::getAlias('@app/timestamp.txt'), time()); $this->stdout('Done!', Console::FG_GREEN, Console::BOLD); $this->stdout(PHP_EOL); } }
After all is done, run the command in a shell:
./yii cron/timestamp
Then, check the response text and the existence of a new file, namely timestamp.txt
.
A console command is defined as a controller class that extends from yiiconsoleController
. In the controller class, you define one or more actions that correspond to the subcommands of the controller. Within each action, you write code that implements the appropriate tasks for that particular sub-command.
When running a command, you need to specify the route to the controller action. For example, the route migrate/create
invokes the sub-command that corresponds to the MigrateController::actionCreate()
action method. If a route offered during the execution does not contain an action ID, the default action will be executed (as with a web controller).
Take care that your console controllers are placed in the directory defined in the c
ontrollerNamespace
option in your web/console.php
config.
controllerNamespace
3.137.181.52