7

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

2 Answers 2

8

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

setting up a user service is a bit more involved than I would like to get this basic function (grabbing the global param)
S2 does not expose parameters to the global space. If you really feel you need to then access $kernel and pull it from there. But you really should use a service.
4

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.

2 Comments

I am pulling the lat/long of the lphysical location entered during prepersist.
You can still do that with a service. Here's a bundle which does exactly that: github.com/dustin10/VichGeographicalBundle - Using events, it checks for entities which need coordinates added, and it queries, and updates them when being saved. Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.