Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Symfony2 global parameter in entity class

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

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

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

P.S. The value is an API key for a service I am pulling info from during prepersist. Best practice is to keep keys/passwords in parameters.ini

like image 486
MrGlass Avatar asked Jul 24 '12 15:07

MrGlass


2 Answers

Best practice is to use a service to persist your entity. This one would inject the container and set your parameter when you call your updateMyEntity() service method.

Inside your controller (or whatever you want):

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

Inside the UserService:

public function update(User $user) {
    $user->setSomeParameter($this->container->getParameter('value'));
    $this->em->persist($user);
}
like image 125
Florent Avatar answered Sep 25 '22 00:09

Florent


In addition to Florent's answer, Entities are meant to be purely data objects. They should not know about any other variables or services within your application. I'm more curious about why your entity needs to know anything about an API key that is system-wide. With very little background information, I'd say you should rethink what you are trying to do.

You need a service to interact with the API, ideally configured through the container. I don't see what that has to do with an entity.

like image 20
Adrian Schneider Avatar answered Sep 27 '22 00:09

Adrian Schneider