How can I make some classes and objects accessible from all MVC layers?
For example I want to access to current user's profile and config.ini
file globally.
In Zend Framework 1.x I was using Zend_Registery for this purpose.
How can I make some classes and objects accessible from all MVC layers?
For example I want to access to current user's profile and config.ini
file globally.
In Zend Framework 1.x I was using Zend_Registery for this purpose.
You can use the DI container for this.
A simple way to access your config is to create a lambda function in your bootstrap like so:
$configFile = require(ROOT_PATH . '/web/config/global.php');
// Create the new object
$config = new \Phalcon\Config($configFile);
// Store it in the Di container
$this->di['config'] = $config;
Accessing this object from a controller is as simple as:
$config = $this->config;
From any other part of your application, you can always grab the Di container and access it from there like so:
$di = \Phalcon\DI\FactoryDefault::getDefault();
$config = $di->config;
Have a look at a bootstrap example here. It showcases how services are registered in the Di container.
As per the current users profile, you can always use the Session component to store that information and retrieve it at will in the same manner as the config above.
Finally you can register your own Registry service in Phalcon. I have an example here if you are interested.
I built an extended skeleton for some phalcon issues. This was one of them.
Checkout the project here: https://github.com/alanbarber111/cloud-phalcon-skeleton
But, basically Cloud::app()->getPhalconDi()
or Cloud::app()->getPhalconRouter()
or Cloud::app()->getPhalconApplication()
can be called from anywhere in the app
It's worth mentioning that Phalcon includes a built in registry service which I found helpful:
https://docs.phalconphp.com/en/latest/api/Phalcon_Registry.html