Reputation: 681
Hi I am trying to get the logged in user while I am saving an object in a propel model class.
I see from all the docs on symfony2 that you get the user by:
$this->get('security.context')->getToken()- >getUser()
and inside twig
app.user
but how do I get the same information from inside the model/entity
EDIT:
Ok so a bit more of what I am trying to do as I cannot see really how to do this. Ive looked at dependency injection injection but not sure it is really right for what I want to do.
I have a entity class called Event and another called UserToEvent in Event->postSave() I want to create the UserToEvent object and save that into the database with the new event.id and the user.id
I dont really think this requires a "service" as defined here as this says a service is "some sort of "global" task" and to have to inject the user into the Event object every time I want to save the a new object also seems a bit of a waste. Usually I would expect to be able to do something along the lines of Application::getUser(); but this does not appear to be possible.
Upvotes: 2
Views: 2573
Reputation: 36191
Use dependency injection.
Inject security context or user to the class you need it. It's the approach you should start following while working with Symfony2 apps.
You can inject services either manually or using DIC. Since you want to use it inside the entity class you'll probably need to pass the dependency
in a constructor:
class Page
{
private $user = null;
public function __construct($user)
{
$this->user = $user;
}
}
or setter:
class Page
{
private $user = null;
public function setUser($user)
{
$this->user = $user;
}
}
or as a method parameter:
class Page
{
public function doSomething($user)
{
// do something with $user
}
}
Good series of articles on dependency injection: http://fabien.potencier.org/article/11/what-is-dependency-injection
Upvotes: 3