We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

No response is sent to the base controller

Good day. This question. In the base controller I send the response manually. It seems this all has to stop, but after that, this same response is overwritten in the destination controller. Example:

class RestController extends \Phalcon\Mvc\Controller
{
    public function initialize()
    {
        return $this->response->setStatusCode(400)->setJsonContent(['errors' => 'Token is null'])->send();
    }
}

class TestController extends \Controller\RestController
{
    public function getTestAction()
    {
        return $this->response->setStatusCode(200)->setJsonContent(['Controller']);
    }
}

The resulting display is ["Controller"]. Although this design worked in version 1.3.5.

I don't know about 1.x versions, but in 2.x initialize cannot stop the dispatch loop. Try using the beforeExecuteRoute

https://docs.phalcon.io/en/latest/reference/dispatching.html#dispatch-loop-events

I don't know about 1.x versions, but in 2.x initialize cannot stop the dispatch loop. Try using the beforeExecuteRoute

https://docs.phalcon.io/en/latest/reference/dispatching.html#dispatch-loop-events

I added the event handler, but it still displays "["Controller"]". Do you have any ideas?

$di->set('dispatcher', function() use ($di) {
    $eventsManager = new \Phalcon\Events\Manager();
    $eventsManager->attach('dispatch:beforeExecuteRoute', new Plugin\Security);
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setEventsManager($eventsManager);
    return $dispatcher;
});

class Security extends Plugin
{
    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        $this->response->setStatusCode(400)->setJsonContent(['errors' => 'Token is null'])->send();
    }
}

While that solved the problem for a crutch.

class Security extends Plugin
{
    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        $this->response->setStatusCode(400)->setJsonContent(['errors' => 'Token is null'])->send();
        die();
    }
}


351
Accepted
answer
edited Oct '15

If you want to stop the active operation, use return False after setting the status code and content.
When done properly it will work for the events marked as "Yes" under "Can stop operation?": https://docs.phalcon.io/en/latest/reference/dispatching.html#dispatch-loop-events