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

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 (https://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.



98.9k
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.