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

Auth check in initialize method

Hey guys!

<?php

    use Phalcon\Mvc\Controller;

    class AdminController extends Controller {

        public function initialize() {

            if(!$this->session->has('user')) {
                // fix a recursion calling if call /adm/login
                if($this->dispatcher->getActionName() !== 'login') {

                    $this->dispatcher->forward([
                        'controller' => 'admin',
                        'action' => 'login',
                    ]);

                }
            }

        }
        public function indexAction() {

            echo 'HELLO_ADM';

        }

        public function loginAction() {

            echo 'LOGIN_PAGE';

        }

    }

GET /adm returned "HELLO ADM LOGIN PAGE". why? why not "LOGIN _ PAGE" only? (Session is empty).

What happens if you put an echo statement in your initialize() method?



783

just add "return false;" after dispatcher forward.



5.1k

do it in beforeExecuteRoute function, ininitialize don't stop the current action


    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
            if(!$this->session->has('user')) {
                // fix a recursion calling if call /adm/login
                if($dispatcher->getActionName() !== 'login') {

                    $dispatcher->forward([
                        'controller' => 'admin',
                        'action' => 'login',
                    ]);

                    return false;

                }
            }
    }