Accessing Symfony2 global parameter in entity class

13,876

Solution 1

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);
}

Solution 2

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.

Share:
13,876
MrGlass
Author by

MrGlass

Crazy Jewish Hacker & Developer

Updated on June 24, 2022

Comments

  • MrGlass
    MrGlass almost 2 years

    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