Question

I have 2 Controllers, TEST1Controller and TEST2Controller

In TEST2Controller I have a initialize() function setting value of a property.

If I try to access TEST2Controller directly from the browser, everything works perfectly.

But when I call a TEST2Controller method from TEST1Controller, it seems that initialize() function is not being called in TEST2Controller.

TEST1Controller:

namespace Modcont\Controller;

use Modcont\Controller\Test2Controller;

class Test1Controller extends BaseController
{

    function gettestAction()
    {
       $t = new Test2Controller(); // calling TEST2 Controller Method Within TEST1 Controller
       echo $t->dotestAction(" MYAPP ");
    }    
}

TEST2Controller:

namespace Modcont\Controller;

class Test2Controller extends BaseController
{   
    public $prefix;
    function initialize()
    {
        $this->prefix = 'your name is';
    }

    function dotestAction($name)
    {
        return $this->prefix.' : '.$name; 
    } 

}
Was it helpful?

Solution

Phalcon offers two ways for controller initialization, thy are the initialize and onContruct methods. The basic difference between these two methods is that initialize is called only when a controller is created by the framework to proceed with the execution of an action. Since you instantiating a controller object ad-hoc, initialize will not be called, only onConstruct will. So you'll need to put your initialization logic there:

function onConstruct()
{
    $this->prefix = 'your name is';
}

Also, implementing native constructors in controller is discouraged, but if you do so, make sure to call the parent constructor in your own constructor: parent::__construct();.

All this information can be found in the Docs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top