代理方法在 sfGuardSecurityUser 中不起作用
我正在 Symfony 中开发一个过滤器来跟踪用户在应用程序中执行的某些请求。为了检索当前用户,我使用 getContext() 方法:
$user = $this->getContext()->getUser();
然后我尝试访问其属性:
...
$username = $user->getUsername();
...
问题是 Symfony 引发以下异常:调用成员函数 getUsername () 在... sfGuardSecurityUser.class.php 中的非对象上,除非我以这种方式检索用户:
$user = $this->getContext()->getUser()->getGuardUser();
根据 sfDoctrineGuardUser 文档(和源代码)有这样的代理方法:
public function getUsername()
{
return $this->getGuardUser()->getUsername();
}
为什么代理方法不起作用?
更新
经过几周的开发,问题再次出现。这次是使用 $sf_user
变量的视图。我可以通过以下方式获得ID
$sf_user->getGuardUser()->getId()
,但不能通过
$sf_user->getId()
以下方式在我自己的答案中进行解释。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来
$this->getGuardUser()
返回null,你必须找出原因。It seems that
$this->getGuardUser()
returns null, you have to find out why.感谢@Matt Gibson 评论,我回顾了 sfDoctrineGuardPlugin 的安装过程。看来我在某个地方犯了一个拼写错误,因为现在一切都运行良好,而且
,
但是,我认为这些代理方法可以改进,因为它缺少
getId
方法。您可以检索除 ID 之外的几乎所有内容,而 ID 必须使用长格式检索: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
and
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:只需将代理方法添加到您的 User 类中即可,代理方法并不多。
或者,如果您喜欢魔法,您可以定义虚拟 __call() 方法并将所有未定义的方法重定向到父类。
Just add your proxy methods to your User class, there aren't that many of them.
Or, if you like magic, you can define virtual __call() method and redirect all undefined methods to parent class.
我在我拥有的 sfGuardSecurityUser.class.php 版本中发现了一个错误。查看第 202 行并更改此...这导致 IF 语句不触发,因此在需要时不返回用户。
到
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.
to