Snippet: Symfony User - Access the User Object

The following snippets provide access to the Symfony User object from various parts of a Symfony project.

Template / View

  $user = $sf_user;

Model or Form

  $user = sfContext::getInstance()->getUser();

Note: the context isn't setup when using the command line, therefore if you use this in the save() method of an object and try to populate the object from a data-load it will throw an error: 'The "default" context does not exist'.

Action

  $user = $this->getUser();

or

  $user = sfContext::getInstance()->getUser();

sfGuardUser and sfGuardUserProfile

sfGuard is a popular plugin for Symfony which provides a complete set of tools for managing users, groups, permissions and profiles. Once the user object has been retrieved as above, the sfGuard user and profile are accessed as follows:

Template / View

  $profile = $user->getGuardUser()->getProfile();

A Note on Snippets: When using frameworks such as Symfony it is often the simplest pieces of code which are the hardest to either find or remember. These snippets are placed here for my own reference and will hopefully be useful to others. If you find them useful or have any suggestions, please let me know.