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.

Undefined variable in View using setVar() function when set DI services

I'm using dispatcher to dispatch custom controller, action, and view:

$Controller = 'contact';
$Action = 'index';
$this->getDI()->get('dispatcher')->setControllerName($Controller);
$this->getDI()->get('dispatcher')->setActionName($Action);
$this->getDI()->get('dispatcher')->dispatch();
$ViewController = $this->getDI()->get('dispatcher')->getControllerName();
$ViewAction = $this->getDI()->get('dispatcher')->getActionName();
$this->getDI()->get('view')->start();
$this->getDI()->get('view')->render($ViewController, $ViewAction, $e);

It is working fine and the controller is being dispatched and view is rendering correctly, but there is one problem in view variables when I set them in the controller:

$this->view->setVar('A', 1);
// or
$this->view->A = 1;

Then in view contact/index.phtml when I try to print $A variable:

echo $A;

I got the following error: Notice: Undefined variable: A in ..XXXXX/app/views/contact/index.phtml on line 1

Any suggestions on how can I assign variables to be used in views. Thank you



19.6k
edited Aug '14

Maybe (I didn't use dispatcher) would be:

$this->getDI()->get('view')->setVar('A', 1);
edited Aug '14

Hi David, It didn't work! that worked when I was using default app. thank you



84.5k
Accepted
answer
edited Aug '14

Make sure you're registering the 'dispatcher' and 'view' services as 'shared':

$di->set('dispatcher', function (){
        //...
}, true);
$di->set('view', function (){
        //...
}, true);
edited Aug '14

Yes it worked! thank you Phalcon. Can you tell me what is the effect of shared service exactly, and why doesn't it work before even I was setting view service using DI which could be enough ?



84.5k

When a service is not shared every time you access it, the DI returns a new instance:

#non shared
$this->getDI()->get('dispatcher'); // new Dispatcher() 
$this->getDI()->get('dispatcher'); // new Dispatcher();

#shared
$this->getDI()->get('dispatcher'); // new Dispatcher() 
$this->getDI()->get('dispatcher'); // same instance created before