本文介绍了从 symfony 2.1 (Doctrine) 中的实体获取服务容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在学说中使用实体即服务(使用 Symfony 2.1).

How to use entity as service in doctrine (Using Symfony 2.1).

示例用法:

<?php

namespace MyNamespace;

class MyEntity
{
  protected $container = NULL;
  public function __construct($container)
  {
    $this->container = $container;
  }

  /**
   * @ORMPrePersist
   */
  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.

推荐答案

实体是一种数据模型,应该只保存数据(并且不依赖于服务).如果您想在发生某个事件时修改模型(在您的情况下为 PrePersist),您应该考虑制作一个 学说听众.定义监听器的时候可以注入容器:

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: AcmeSearchBundleListenerYourListener
        arguments: [@your_service_dependency_or_the_container_here]
        tags:
            - { name: doctrine.event_listener, event: prePersist }

这篇关于从 symfony 2.1 (Doctrine) 中的实体获取服务容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 13:43