4

How can I pass variables to main view, not just the view for controller.

in fact I want to share a piece of data across all views. how can I do that in phalcon.

for instance, in Laravel, I can use:

View::share('variable', $value);

Pars
  • 4,932
  • 10
  • 50
  • 88

3 Answers3

4

With Phalcon you don't need any additional functions to pass data into the layout. All variables assigned in the action are available in the layout automatically:

Controller:

class IndexController extends \Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        $this->view->bg    = 'green';
        $this->view->hello = 'world';
    }
}

Main layout:

<html>
<body style="background: <?php echo $bg ?>">

    <?php echo $this->getContent(); ?>

</body>
</html>

Action view:

<div>
    <?php echo $hello ?>
</div>

You will see text 'world' on the green background.

Phantom
  • 1,704
  • 4
  • 17
  • 32
  • this is equivalent to `$this->view->setVar('x',$x);`. this only set x for current view, I want to have variable across all views, it's not related to any Controller. – Pars Jun 27 '14 at 15:10
3

You could create a service for that - if this is simple variable it will be an overkill but it will work.

<?php 
    // In your bootstrap file
    $di->setShared('variable', 41);
?>

Then in any view (or a controller or any DI injectable) it will be avaiable as $this->variable. Ie:

// some view
<?php echo $this->variable; ?>

// or using volt
{{ variable }}

The variable of course can be an object. Personally for such simple variables I'm using config object, ie: {{ config.facebook.fbId }}.

jodator
  • 2,445
  • 16
  • 29
  • 1
    This is a great answer, but there is a syntax error. To create a service in PhalconPHP the second param has to be a function, like this: $di->setShared('variable', function(){ return 41; }); – Salvi Pascual Jan 08 '15 at 23:39
3

I think better would be to create BaseController - parent controller everyone extends. And then using event add shared data to view after execution of each action:

<?php

class ControllerBase extends \Phalcon\Mvc\Controller
{
    protected $_sharedData = [];

    public function initialize()
    {

      // set shared data for all actions
      this->_sharedData = [
         'sharedVar' = 1,
         'overrideMe' = false
      ];
    }

    public function afterExecuteRoute($dispatcher)
    {
        // Executed after every found action
        $this->view->setVar('sharedData', $this->_sharedData);
    }
}

In child controller

<?php

class IndexController extends ControllerBase
{
    public function initialize()
    {
        parent::initialize();

        // override shared variable for all Index actions
        $this->_sharedData['overrideMe'] = true;
    }

    public function homeAction()
    {
        // add custom variable to shared data
        $this->_sharedData['customVar'] = -1;
    }
}
Alex Kalmikov
  • 1,865
  • 19
  • 20