在实体类中访问Symfony2全局参数 [英] Accessing Symfony2 global parameter in entity class
问题描述
我在我的parameters.ini文件中存储了一个值,我需要在模型的prepersist方法期间访问它.
I have a value stored in my parameters.ini file, and I need to access it during the prepersist method of my model.
通常我使用$this->container->getParameter('value');
,但是该容器在实体中不可用.
Normally I use $this->container->getParameter('value');
, but the container is not available in the entity.
是否可以在实体类中获取参数?
Is there a way to get parameters within an entity class?
P.S.该值是我在prepersist期间从中获取信息的服务的API密钥.最佳做法是将键/密码保留在parameter.ini中
P.S. The value is an API key for a service I am pulling info from during prepersist. Best practice is to keep keys/passwords in parameters.ini
推荐答案
最佳做法是使用服务来保留您的实体.当调用 updateMyEntity()
服务方法时,这将注入容器并设置参数.
Best practice is to use a service to persist your entity. This one would inject the container and set your parameter when you call your updateMyEntity()
service method.
在控制器内部(或您想要的任何内部):
Inside your controller (or whatever you want):
$user = new User('foo');
$user->setSomeProperty('bar');
$userService->update($user);
在UserService
内:
public function update(User $user) {
$user->setSomeParameter($this->container->getParameter('value'));
$this->em->persist($user);
}
这篇关于在实体类中访问Symfony2全局参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!