php 从 symfony 2.1 (Doctrine) 中的实体获取服务容器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13152610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get service container from entity in symfony 2.1 (Doctrine)
提问by ZhukV
How to use entity as service in doctrine (Using Symfony 2.1).
如何在学说中使用实体即服务(使用 Symfony 2.1)。
Example usage:
用法示例:
<?php
namespace MyNamespace;
class MyEntity
{
protected $container = NULL;
public function __construct($container)
{
$this->container = $container;
}
/**
* @ORM\PrePersist
*/
public function()
{
// Must call to container and get any parameters
// for defaults sets entity parameters
$this->container->get('service.name');
}
}
As a result, I need to get access to the entire container.
因此,我需要访问整个容器。
回答by alex88
EDIT: THIS IS NOT THE PREFERRED WAY, it's the only way to get service container inside an entity, it's not a good practice, it should be avoided, but this just answers the question.
编辑:这不是首选方式,这是在实体中获取服务容器的唯一方法,这不是一个好的做法,应该避免,但这只是回答了问题。
In case you still want the container and/or repository you can extend a base abastractEntity like this:
如果您仍然需要容器和/或存储库,您可以像这样扩展基本的 abastractEntity:
<?php
namespace Acme\CoreBundle\Entity;
/**
* Abstract Entity
*/
abstract class AbstractEntity
{
/**
* Return the actual entity repository
*
* @return entity repository or null
*/
protected function getRepository()
{
global $kernel;
if ('AppCache' == get_class($kernel)) {
$kernel = $kernel->getKernel();
}
$annotationReader = $kernel->getContainer()->get('annotation_reader');
$object = new \ReflectionObject($this);
if ($configuration = $annotationReader->getClassAnnotation($object, 'Doctrine\ORM\Mapping\Entity')) {
if (!is_null($configuration->repositoryClass)) {
$repository = $kernel->getContainer()->get('doctrine.orm.entity_manager')->getRepository(get_class($this));
return $repository;
}
}
return null;
}
}
回答by Kristian Zondervan
An entity is a data model and should only hold data (and not have any dependencies on services). If you want to modify your model in case of a certain event (PrePersist in your case) you should look into making a Doctrine listenerfor that. You can inject the container when defining the listener:
实体是一个数据模型,应该只保存数据(并且不依赖于服务)。如果您想在发生某个事件(在您的情况下为 PrePersist)时修改您的模型,您应该考虑为此创建一个Doctrine 侦听器。您可以在定义侦听器时注入容器:
services:
my.listener:
class: Acme\SearchBundle\Listener\YourListener
arguments: [@your_service_dependency_or_the_container_here]
tags:
- { name: doctrine.event_listener, event: prePersist }

