Phalcon中的交叉控制器变量 [英] Cross controller variables in Phalcon

查看:102
本文介绍了Phalcon中的交叉控制器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使代码保持干燥,我希望能够定义跨控制器"变量.

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?

蒂姆

推荐答案

您始终可以使用Di容器.

You can always use the Di container.

一旦您在Di中注册了组件,就可以通过magic方法在控制器中使用它.例如:

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);

最后,Di容器还可以充当注册表,在其中存储您可能要在应用程序中使用的项目.

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

有关引导和访问控制器中对象的示例,请查看 phalcon/website 存储库.它实现了自举和基本控制器模式.

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.

这篇关于Phalcon中的交叉控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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