Global access to some component in Phalcon

2019-08-03 03:00发布

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.

3条回答
走好不送
2楼-- · 2019-08-03 03:25

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-03 03:29

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

查看更多
Explosion°爆炸
4楼-- · 2019-08-03 03:38

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

查看更多
登录 后发表回答