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.

Bug in forwarding to the same controller?

Hi, I need to do forward to another action in the same controller but after forwarding initialize constructor doesn`t execute:

class ProfileController extends ControllerBase
{
    public function initialize(){
        parent::initialize();
        $this->logger->alert('I`m Index Initaialize');
    }

    public function indexAction(){
        $this->logger->alert('I`m Index Action');
    }

    public function testAction(){
        $this->logger->alert('I`m Test Action');
    }
}

Then, I go to testAction (http://localhost/profile/test) and in logs I have the following output:

[Sun, 12 Oct 14 15:10:54 +0400][ALERT] I`m Index Initaialize
[Sun, 12 Oct 14 15:10:54 +0400][ALERT] I`m Test Action
[Sun, 12 Oct 14 15:10:54 +0400][ALERT] I`m Index Action

So, we can see, than initialize constructor didn't execute second time (after forwarding to the same controller), but I need initialize constructor for every action, e.g. I set template before for view in initialize constructor and It doesn't work after forwarding.

Thanks for your help.



84.6k
Accepted
answer

Not a bug, initialize is not a constructor and it's not expected to work as a one, if you want something like a construtor you can use 'onConstruct':

class ProfileController extends ControllerBase
{
    public function onConstruct(){
        $this->logger->alert('I`m Index onConstruct');
    }

    public function indexAction(){
        $this->logger->alert('I`m Index Action');
    }

    public function testAction(){
        $this->logger->alert('I`m Test Action');
    }
}

However, according to the behavior you're expecting it's better to use 'beforeExecuteRoute' there:

class ProfileController extends ControllerBase
{
    public function beforeExecuteRoute(){
        $this->logger->alert('beforeExecuteRoute');
    }

    public function indexAction(){
        $this->logger->alert('I`m Index Action');
    }

    public function testAction(){
        $this->logger->alert('I`m Test Action');
    }
}

Thank you, Phalcon, now everything is clear.