5

Within my project, I've created a "core" directory which contains certain classes and methods called throughout the controllers. I've defined a configuration parameters in my bootstrap file like so:

private function loadConfig ()
{
    // Bootstrap
    $configFile = __DIR__ . '/../config/config.json';

    // Create the new object
    $config = json_decode ( file_get_contents ( $configFile ) );

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

I want to be able to access these configuration values in my "core" classes.

What do I do?

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
Ayush Sharma
  • 265
  • 4
  • 13

3 Answers3

6

There are several ways to get a reference to the service you registered with the Dependency Injector. However, to make sure you are getting the same instance of the service and not a newly generated one, then you need to use the getShared method:

$this->getDI()->getShared('config');

Doing so ensures you are getting the highest performance possible, and minimizing memory footprint.

Scriptonomy
  • 3,975
  • 1
  • 15
  • 23
2

in your controller class, call config by

$this->config
Fazal Rasel
  • 4,446
  • 2
  • 20
  • 31
2

You can access to the services from any classes which implements Phalcon\Di\Injectable

  • Phalcon\Mvc\Controller
  • Phalcon\Mvc\User\Component
  • Phalcon\Mvc\User\Module
  • Phalcon\Mvc\User\Plugin
  • etc

Examples:

$this->getDI()->get('config');

// The same as $this->config
$this->getDI()->getShared('config');
serghei
  • 3,069
  • 2
  • 30
  • 48