[英]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.