Access the Symfony2 global parameter in an entity class

I have a value stored in the parameters.ini file and I need to access it during the prepersist method of my model.

I usually use $this->container->getParameter('value'); but the container is not available in the object.

Is there a way to get parameters inside an entity class?

PS The value is the API key for the service with which I retrieve information during the forwardbyst. Best practice is storing keys / passwords in .ini options

+6
source share
2 answers

Best practice is to use a service to preserve your essence. This container will enter the container and set it when the updateMyEntity() method is updateMyEntity() .

Inside your controller (or what you want):

 $user = new User('foo'); $user->setSomeProperty('bar'); $userService->update($user); 

Inside UserService :

 public function update(User $user) { $user->setSomeParameter($this->container->getParameter('value')); $this->em->persist($user); } 
+8
source

In addition to Florent's answers, entities should be purely data objects. They should not be aware of any other variables or services in your application. I'm more curious why your object should know anything about an API key, which is a system-wide. With very little background information, I would say that you have to rethink what you are trying to do.

You need a service for interacting with the API, ideally configured through the container. I do not see that this is connected with the essence.

+4
source

Source: https://habr.com/ru/post/921221/


All Articles