[英]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 创建的(从用户请求中查询)。
我通常会编写一个上下文类,它需要请求和存储库来返回依赖项(如此处所述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
}
如何解决通过深度嵌套结构创建的依赖项?
添加到我对原始帖子的评论中,一旦您将实体作为方法参数传递,您就可以将其设置为类变量,即:
$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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.