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

Dispatcher not working as expected

I'm creating a login portal and if a user is not logged in but tries to access a page that they should be logged in for the system should show a 404 page.

I read that you can internally redirect requests using the $this->dispatcher->forward() method, however it doesn't render the 404 page, but simply continues executing the indexAction() method and the any response in the Index::notFound method is never shown, am I doing something wrong?

(I read the documentation on the dispatcher here)

My code:

class LoginController extends ControllerBase {
    public function initialize() {
        parent::initialize();

        if ($this->session->get('logged-in') == null) {
            $this->dispatcher->forward([
                "controller" => "Index", 
                "action" => "notFound"
            ]);
        }
    }

    public function indexAction() {
        exit("You are logged in")
    }
}   
edited Oct '15

the controller name must start with small letter

        $this->dispatcher->forward([
            "controller" => "index", 
            "action" => "notFound"
        ]);

after forward you might have to do "return;' too to stop the current process

but for such things I would rather recommend you using the ACL, and beforeDispatchRoute()

https://docs.phalcon.io/en/latest/reference/dispatching.html#handling-not-found-exceptions



5.0k

I am also facing the same problem right now. I have tried the securityplugin.php class from INVO, filter is working fine and it catches the ($allowed != Acl::ALLOW) condition but the dispatcher is only displaying blank screen. anyone knows what the problem is? It seems that it is not displaying the show401 action from ErrorsController

    if ($allowed != Acl::ALLOW) {
        $dispatcher->forward(array(
            'controller' => 'errors',
            'action'     => 'show401'
        ));
        $this->session->destroy();
        return false;
    }


5.0k

It's ok now, apparently , I forgot to add the new action show401 in $publicResources

$publicResources = array(
            'errors'      => array('show401')
);