Phalcon and cron. Phalcon cli tasks
lang_of_article_differ
want_proper_trans
start
If you want to exec curl tasks with phalcon you need to have folowing things up in you app:
SITE_PATH/cli/app.php // console application file which is an entry-point for cli app
SITE_PATH/app/tasks // folder for the future tasks
SITE_PATH/app/tasks/MainTask.php // the task we going to review in example
If some file not exists in your project yet - create it now!
example of the cli.php
:
<?php
/**
* Init loader
*/
$loader = new \Phalcon\Loader();
$loader->registerDirs(['app/tasks/'])
->register();
/**
* Setup dependency injection
*/
$di = new Phalcon\DI();
/**
* Run application
*/
$app = new Phalcon\CLI\Console();
$app->setDI($di);
$app->handle($argv);
making tasks
when you're done with configuration, there's the time to start making actually tasks. Each task is a separate file which has pretty the same funcionality as controllers in phalcon's app. Let's have a look at task which removes unactivated users from the site's database:
<?php
namespace app\Tasks;
use app\Models\User;
use Phalcon\Cli\Task;
class MainTask extends Task {
public function mainAction() {
}
public function removeUnactivatedUsersAction() {
$config = $this->di->get('config');
$users = User::find([
'conditions' => 'registered < :date: AND is_activated = "false" AND is_removed = "false"',
'bind' => [
'date' => date('Y-m-d H:i:s', time() - $config['application']['deleteUnactivatedUserAfter'])
]
]);
foreach ($users as $userToDeactivate) {
$userToDeactivate->is_available = false;
$userToDeactivate->is_removed = true;
$userToDeactivate->save();
}
}
}
Task class should extend Phalcon\Cli\Task
to facilitate cli functions.
Different action methods as they do in phalcon's controllers must end with Action
keyword.
If you want to use services you use in your phalcon app you should add them into Cli dependency injection container. As you mentioned above, i've simply created default di container. The trick is that your cli app could have different from website's functionalities and there is no need in most of the services you use for the website.
Whenever you finish your task class you could invoke the action by typing in terminal php PATH_TO_CLI/cli.php taskName actionName
. This makes easy to execute the tasks in the cron like that:
1 0 * * * php PATH_TO/app.cli main removeUnactivatedUsers # remove unactivated users once a day
Have a nice day!