Php Symfony get实体存储库类内的会话变量

Php Symfony get实体存储库类内的会话变量,php,symfony,Php,Symfony,我试图在Symfony2实体存储库类中获取一个会话变量,但不确定如何完成此任务 基本上我只是这样做: $this->get('session')->set('cart_id', $cartId); 谁能给我指一下正确的方向吗。谢谢。那不是你想做的事。它的设计很糟糕。您应该创建一个服务来读取会话变量并将其设置为实体 你不应该在实体记忆体中做那样的事。您可以在控制器或服务中执行此操作。 您可以通过将实体存储库声明为服务来实现它,如下所示: parameters: entity.

我试图在Symfony2实体存储库类中获取一个会话变量,但不确定如何完成此任务

基本上我只是这样做:

$this->get('session')->set('cart_id', $cartId);

谁能给我指一下正确的方向吗。谢谢。

那不是你想做的事。它的设计很糟糕。您应该创建一个服务来读取会话变量并将其设置为实体

你不应该在实体记忆体中做那样的事。您可以在控制器或服务中执行此操作。 您可以通过将实体存储库声明为服务来实现它,如下所示:

parameters:
    entity.sample_entity: "AppBundle:SampleEntity"

services:
    sample_entity_repository:
        class: AppBundle\Repository\SampleEntityRepository
        factory: ["@doctrine", getRepository]
        arguments:
            - %entity.sample_entity%
        calls:
          - [setSession, ["@session"]]
class SampleRepository extends EntityRepository
{
   private $entity;
   private $session;

   public function __construct(SampleEntity $entity)
   {
      $this->entity = $entity;
   }

   public function setSession(Session $session)
   {
      $this->session = $session;
   }
   .....
}
您可以在存储库类中创建setSession方法,如下所示:

parameters:
    entity.sample_entity: "AppBundle:SampleEntity"

services:
    sample_entity_repository:
        class: AppBundle\Repository\SampleEntityRepository
        factory: ["@doctrine", getRepository]
        arguments:
            - %entity.sample_entity%
        calls:
          - [setSession, ["@session"]]
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\u id',$cartId)

您需要将repo声明为服务,注入会话服务,然后将repo用作服务(而不是通过条令)。将会话与存储库层连接不是最好的主意。也许您可以从控制器/服务上的会话中获取所有必需的数据,然后将它们作为方法调用参数传递给存储库。我在实体中使用回调来验证会话中存在的数据。我应该像上面那样做,还是做其他事情?谢谢