Get service container from entity in symfony 2.1 (

2019-01-14 08:54发布

问题:

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.

回答1:

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 }


回答2:

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:

<?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;

    }

}