[英]Get service container from entity in symfony 2.1 (Doctrine)
How to use entity as service in doctrine (Using Symfony 2.1). 如何在doctrine中使用实体作为服务(使用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. 因此,我需要访问整个容器。
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;
}
}
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 listener for that. 如果你想在某个事件(在你的情况下是PrePersist)的情况下修改你的模型,你应该考虑为它创建一个Doctrine监听器。 You can inject the container when defining the listener: 您可以在定义侦听器时注入容器:
services:
my.listener:
class: Acme\SearchBundle\Listener\YourListener
arguments: [@your_service_dependency_or_the_container_here]
tags:
- { name: doctrine.event_listener, event: prePersist }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.