在我的项目中,我创建了一个"core"目录,其中包含在整个控制器中调用的某些类和方法。我在引导程序中定义了一个配置参数,如下所示:
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 );
}
我希望能够在我的"核心"类中访问这些配置值。
我该怎么办?
有几种方法可以获取对向依赖项注入器注册的服务的引用。但是,为了确保您获得的是相同的服务实例而不是新生成的实例,您需要使用 getShared 方法:
$this->getDI()->getShared('config');
这样做可确保您获得尽可能高的性能,并最大限度地减少内存占用。
在你的控制器类中,调用
配置$this->config
您可以从
实现Phalcon'Di'Injectable
的任何类访问服务
-
Phalcon'Mvc'Controller
-
Phalcon'Mvc'User'Component
-
Phalcon'Mvc'User'Module
-
Phalcon'Mvc'User'Plugin
- 等
例子:
$this->getDI()->get('config');
// The same as $this->config
$this->getDI()->getShared('config');