7

In an effort to keep my code DRY I would like to be able to define "cross controller" variables.

Classic example is that I would like access to some config items that are loaded in my bootstap.

What is the best practise method of achieving this?

Tim

Tim
  • 3,091
  • 9
  • 48
  • 64

2 Answers2

7

You can always use the Di container.

Once you register a component in the Di it is available in the controller by the magic method. For instance:

// Bootstrap
$configFile = ROOT_PATH . '/app/config/config.ini';

// Create the new object
$config = new \Phalcon\Config\Adapter\Ini($configFile);

// Store it in the Di container
$this->di->setShared('config', $config);

and in your controller it is as simple as:

$config = $this->config;

If you create a base controller class, you can pass those objects in the view if needed like so:

$this->view->setVar('config', $this->config);

Finally the Di container can act also as a registry, where you store items you might want to use in your application.

For an example of bootstrapping and accessing objects in controllers, have a look at the phalcon/website repository. It implements bootstrapping and base controller patterns among other things.

Nikolaos Dimopoulos
  • 11,495
  • 6
  • 39
  • 67
  • 1
    I know I'm a bit late, but why in this scenario would you use $di->set() over $di->setShared()? –  Mar 06 '14 at 04:04
  • @Spinkzeit `setShared` could be a better use here - you are correct - since the `$config` is really used throughout the app and needs to be a shared object. I have altered my answer accordingly, thanks! – Nikolaos Dimopoulos Mar 06 '14 at 04:51
2

The following is my setup.

[PHP]     5.4.1
[phalcon] 1.2.1

Here is an excerpt from my bootstrap.(/app-root/public/index.php)

    $di = new \Phalcon\DI\FactoryDefault();

    // I'll pass the config to a controller.
    $di->set('config', $config);

    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();

And this is an excerpt from my base controller.(/app-root/app/controllers/ControllerBase.php)

    class ControllerBase extends Phalcon\Mvc\Controller
    {
            protected $config;

            protected function initialize()
            {
                    $this->config = $this->di->get('config');
                    $appName      = $this->config->application->appName;
Sankame
  • 113
  • 9