Search code examples
phpmethodssymfony1proxysfdoctrineguard

Proxy methods not working in sfGuardSecurityUser


I am developing a filter in Symfony to keep track of certain request that users perform within the application. In order to retrieve the current user I use the getContext() method:

$user = $this->getContext()->getUser();

And then I try to access its properties:

...
$username = $user->getUsername();
...

The problem is that Symfony raises the following exception: Call to a member function getUsername() on a non-object in ... sfGuardSecurityUser.class.php, unless I retrieve the user this way:

$user = $this->getContext()->getUser()->getGuardUser();

According to sfDoctrineGuardUser documentation (and source code) there are proxy methods like this:

public function getUsername()
{
    return $this->getGuardUser()->getUsername();
}

Why the proxy method is not working?

UPDATE

After a couple of weeks developing, the problem arose again. This time from a view using the $sf_user variable. I can get the ID with

$sf_user->getGuardUser()->getId()

but not with

$sf_user->getId()

In my own answer below is the explanation.


Solution

  • Thanks to @Matt Gibson comment I reviewed the installation process of sfDoctrineGuardPlugin. It seems I made a typo somewhere because now everything works well, both

    $this->getGuardUser()->getUsername()
    

    and

    $this->getUsername()
    

    However, I think these proxy methods could be improved because it lacks of a getId method. You can retrieve almost everything except ID, which must be retrieved using the long form:

    $this->getGuardUser()->getId()