如何访问外部库中的 Phalcon 配置数据?
How can I access Phalcon configuration data in an external library?
在我的项目中,我创建了一个 "core" 目录,其中包含某些 类 和在整个控制器中调用的方法。我在我的 bootstrap 文件中定义了一个配置参数,如下所示:
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 );
}
我希望能够在我的 "core" 类 中访问这些配置值。
我该怎么办?
在您的控制器 class 中,通过
调用配置
$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');
有几种方法可以获取对您使用依赖注入器注册的服务的引用。但是,要确保您获得的是相同的服务实例而不是新生成的实例,那么您需要使用 getShared 方法:
$this->getDI()->getShared('config');
这样做可以确保您获得尽可能高的性能,并最大限度地减少内存占用。
在我的项目中,我创建了一个 "core" 目录,其中包含某些 类 和在整个控制器中调用的方法。我在我的 bootstrap 文件中定义了一个配置参数,如下所示:
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 );
}
我希望能够在我的 "core" 类 中访问这些配置值。
我该怎么办?
在您的控制器 class 中,通过
调用配置$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');
有几种方法可以获取对您使用依赖注入器注册的服务的引用。但是,要确保您获得的是相同的服务实例而不是新生成的实例,那么您需要使用 getShared 方法:
$this->getDI()->getShared('config');
这样做可以确保您获得尽可能高的性能,并最大限度地减少内存占用。