LargeTuna
LargeTuna

Reputation: 2824

Symfony get session variable inside of entity repository class

I am trying to get a session variable inside of my Symfony2 entity repository class but not quite sure how to accomplish this task.

Basically I am just doing this:

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

Can someone please point me in the right direction. Thanks.

Upvotes: 2

Views: 3584

Answers (2)

Sohrab
Sohrab

Reputation: 120

You shouldn't do something like that in an EntityRepository. You'd do that in a Controller or Service. You can achieve it by declaring the entity repository as a service like the following:

parameters:
    entity.sample_entity: "AppBundle:SampleEntity"

services:
    sample_entity_repository:
        class: AppBundle\Repository\SampleEntityRepository
        factory: ["@doctrine", getRepository]
        arguments:
            - %entity.sample_entity%
        calls:
          - [setSession, ["@session"]]

You create a setSession method in your Repository class like the following:

class SampleRepository extends EntityRepository
{
   private $entity;
   private $session;

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

   public function setSession(Session $session)
   {
      $this->session = $session;
   }
   .....
}

Then in another function set the session variable like $this->session->set('cart_id', $cartId);

Upvotes: 0

Tobias Nyholm
Tobias Nyholm

Reputation: 1152

That is not something you want to do. It smells bad design. You should create a service that reads the session variable and sets it to the entity.

Upvotes: 2

Related Questions