全局访问Phalcon中的某些组件 [英] Global access to some component in Phalcon

查看:88
本文介绍了全局访问Phalcon中的某些组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使所有MVC层都可以访问某些类和对象?

How can I make some classes and objects accessible from all MVC layers?

例如,我想全局访问当前用户的个人资料和config.ini文件.

For example I want to access to current user's profile and config.ini file globally.

在Zend Framework 1.x中,我为此使用Zend_Registery.

In Zend Framework 1.x I was using Zend_Registery for this purpose.

推荐答案

您可以使用一种访问配置的简单方法是在您的引导程序中创建一个lambda函数,如下所示:

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;

从应用程序的任何其他部分,您始终可以抓取Di容器并从那里访问它,如下所示:

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;

此处查看引导程序示例.它展示了如何在Di容器中注册服务.

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.

最后,您可以在Phalcon中注册您自己的注册服务.如果您有兴趣,我可以在此处进行示例.

Finally you can register your own Registry service in Phalcon. I have an example here if you are interested.

这篇关于全局访问Phalcon中的某些组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆