-3

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

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

我通常会编写一个上下文类,它将请求和存储库返回依赖关系(如此处所述https://blogs.cuttingedge.it/steven/posts/2015/code-smell-injecting-runtime-data-into -组件/)。然而,由于我的依赖依赖于树结构中深度嵌套的数据,这似乎不可行。

/* 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
}

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

4

1 回答 1

-1

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

$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
   }

}
于 2019-09-01T15:28:18.057 回答