Proxy methods not working in sfGuardSecurityUser

638 Views Asked by At

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.

4

There are 4 best solutions below

0
On BEST ANSWER

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()
1
On

It seems that $this->getGuardUser() returns null, you have to find out why.

0
On

Just add your proxy methods to your User class, there aren't that many of them.

class myUser extends sfGuardSecurityUser
{
  public function getId()
  {
    return $this->getGuardUser()->getId();
  }
  public function getUsername()
  {
    return $this->getGuardUser()->getUsername();
  }
}

Or, if you like magic, you can define virtual __call() method and redirect all undefined methods to parent class.

0
On

I found a bug in the version of sfGuardSecurityUser.class.php that I have. Look around line 202 and change this... This was causing that IF statement not to fire thus NOT returning a user when needed.

if (!$this->user && $id = $this->getAttribute('user_id', null, 'sfGuardSecurityUser'))
{

to

$id = $this->getAttribute('user_id', null, 'sfGuardSecurityUser');
if (!$this->user)
{