[英]How to get instance of entity repository in the Form (Type) class in Symfony 2?
[英]Symfony get session variable inside of entity repository class
我試圖在我的Symfony2實體存儲庫類中獲取一個會話變量,但不確定如何完成此任務。
基本上我只是這樣做:
$this->get('session')->set('cart_id', $cartId);
有人能指出我正確的方向嗎? 謝謝。
那不是你想做的。 聞起來不好的設計。 您應該創建一個讀取會話變量並將其設置為實體的服務。
您不應該在EntityRepository中執行類似的操作。 您可以在控制器或服務中執行此操作。 您可以通過將實體存儲庫聲明為如下服務來實現此目的:
parameters:
entity.sample_entity: "AppBundle:SampleEntity"
services:
sample_entity_repository:
class: AppBundle\Repository\SampleEntityRepository
factory: ["@doctrine", getRepository]
arguments:
- %entity.sample_entity%
calls:
- [setSession, ["@session"]]
您可以在Repository類中創建一個setSession方法,如下所示:
class SampleRepository extends EntityRepository
{
private $entity;
private $session;
public function __construct(SampleEntity $entity)
{
$this->entity = $entity;
}
public function setSession(Session $session)
{
$this->session = $session;
}
.....
}
然后在另一個函數中設置會話變量,例如$ this-> session-> set('cart_id',$ cartId);。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.