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?



341

just add "return false;" after dispatcher forward.



2.9k

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;

                }
            }
    }