在 Symfony4 中将 Doctrine-Entity 依赖注入到服务中?

Dependency-Injection of an Doctrine-Entity into a Service in Symfony4?

我正在尝试通过 DI 将实体注入到服务中。

实体是通过 Doctrine-JSON-ODM-library (https://github.com/dunglas/doctrine-json-odm 从数据库中的 JSON-Field(从用户请求中查询)创建的).

我通常会写一个 Context-class,它会将 Request & Repository 带到 return Dependency(如此处所述 https://blogs.cuttingedge.it/steven/posts/2015/code-smell-injecting-runtime-data-into-components/ )。但是,由于我的依赖项依赖于树结构中深度嵌套的数据,这似乎不可行。

/* Doctrine-Entity queried from DB with User-Request-Parameters */
class Page
{
    /**
     * @var Slot[]
     * @ORM\Column(type="json_document", options={"jsonb": true})
     */
    private $slots = [];
}

/* First level of nesting */
class Slot
{
    /** @var Components[] */
    private $components;
}

/* Entity to be injected */
class Component
{
   // multiple data-fields
}

// Service which will need to work with the Component-Data
class ComponentRenderService
{
   // multiple functions which all need (read)-access to the
   // Component-data
}

如何解决通过深层嵌套结构创建的依赖项?

添加到我对原始 post 的评论中,一旦您将实体作为方法参数传递,您可以将其设置为 class 变量,即:

$service->method($entity)

class Service 
{

    private $entity;

    public function method($entity) // You call this somewhere
    {
       // If I understood you correctly, this is what you need
       $this->entity = $entity; // You set it as a class variable (same as DI does in constructor)

       // do stuff to $this->entity
    }


   public function otherMethod()
   {
      // you can access $this->entity here provided that you called `method` first
   }

}