从symfony 2.1(Doctrine)中的实体获取服务容器 [英] Get service container from entity in symfony 2.1 (Doctrine)
本文介绍了从symfony 2.1(Doctrine)中的实体获取服务容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用实例:
<?php
命名空间MyNamespace;
class MyEntity
{
protected $ container = NULL;
public function __construct($ container)
{
$ this-> container = $ container;
}
/ **
* @ ORM\PrePersist
* /
public function()
{
/ /必须调用container并获取任何参数
//默认设置实体参数
$ this-> container-> get('service.name');
}
}
因此,我需要访问整个容器。
解决方案
一个实体是一个数据模型,只能保存数据(而不是依赖于服务)。如果您想在某种情况下修改模型(PrePersist在您的情况下),您应该查看一个 Doctrine监听器。您可以在定义监听器时注入容器:
services:
my.listener:
class: Acme\SearchBundle\Listener\YourListener
参数:[@your_service_dependency_or_the_container_here]
标签:
- {name:doctrine.event_listener,event:prePersist}
How to use entity as service in doctrine (Using 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.
解决方案
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. 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 }
这篇关于从symfony 2.1(Doctrine)中的实体获取服务容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文