We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to call controller action from task?

Hi,

I want to call a controller action in a cli task (to not write the same code again):

namespace app\tasks {
    use Phalcon\CLI\Task;

    class MailTask extends Task {

        public function welcomeAction()
        {
            ...
            $this->dispatcher->forward([
                'namespace' => 'app\controllers',
                'controller' => 'mail',
                'action' => 'sendWelcome',
                'params' => [...]
            ]);

But the dispatcher tries to call a task

$ php cli/app.php mail welcome

$ app\controllers\MailTask handler class cannot be loaded

:( How to do it?



2.8k
Accepted
answer

You are using Phalcon\CLI\Dispatcher, and it trying to add to controller name "Task" postfix. Use a Phalcon\Mvc\Dispatcher instead to load application controllers

Thank you. Solved it by registering an additional dispatcher.

use Phalcon\Mvc\Dispatcher;

$di->set('controllerDispatcher', function() {
    $dispatcher = new Dispatcher();
    return $dispatcher;
});

That was too fast. It does not call the action, but also does not return an error :(

$this->controllerDispatcher->forward([
    'namespace' => 'app\controllers',
    'controller' => 'mail',
    'action' => 'sendWelcome',
    'params' => [...]
]);

It's not a good practice to call controllers over task.

Create a plugin for your sendmail action and register it in task DI. And you could use it in your controller also.

Just move your code from controller to something like /app/plugins/SendMail.php and then register it.

And use $this->controllerDispatcher->dispatch()

Thanks for your explanation! It is working now.

Please, mark this thread as solved then.

It was already ;)