0

我目前正在从一个名为 ZfcUser for Zend 2 的模块中寻找这段代码:

namespace ZfcUser\Controller;

use Zend\Form\Form;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Stdlib\Parameters;
use Zend\View\Model\ViewModel;
use ZfcUser\Service\User as UserService;
use ZfcUser\Options\UserControllerOptionsInterface;

class UserController extends AbstractActionController
{
/**
 * @var UserService
 */
protected $userService;
     .
     .

public function indexAction()
{
    if (!$this->zfcUserAuthentication()->hasIdentity()) {
        return $this->redirect()->toRoute('zfcuser/login');
    }
    return new ViewModel();
}
    .
    .
}

在命名空间 ZfcUser\Controller\Plugin 中:

命名空间 ZfcUser\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
use ZfcUser\Authentication\Adapter\AdapterChain as AuthAdapter;

class ZfcUserAuthentication extends AbstractPlugin implements ServiceManagerAwareInterface
{
/**
 * @var AuthAdapter
 */
protected $authAdapter;
    .
    .
/**
 * Proxy convenience method
 *
 * @return mixed
 */
public function hasIdentity()
{
    return $this->getAuthService()->hasIdentity();
}
/**
 * Get authService.
 *
 * @return AuthenticationService
 */
public function getAuthService()
{
    if (null === $this->authService) {
        $this->authService = $this->getServiceManager()->get('zfcuser_auth_service');
    }
    return $this->authService;
}

我的问题:

  • 从 indexAction() 中,控制器插件被调用而不被实例化($this->zfcUserAuthentication()->hasIdentity()),控制器插件总是这样工作吗?
  • hasIdentity() 中到底发生了什么?我看到 getAuthService() 返回了一些东西,但没有返回 hasIdentity()。我不熟悉这种函数调用的高级类实现,所以我非常感谢这里的任何解释或我应该研究的主题。
4

2 回答 2

1

我无法回答您的第一个问题,但关于您的第二个问题:

代码中的getAuthService()方法返回一个AuthenticationService对象,该对象有一个hasIdentity()方法。

所以有两种不同的hasIdentity()方法:

  • AuthenticationService课堂上(源代码在这里)。
  • ZfcUserAuthentication您正在查看的课程中。

类中的这行代码ZfcUserAuthentication

return $this->getAuthService()->hasIdentity();

做三件事:

  • $this->getAuthService()返回一个AuthenticationService对象。
  • hasIdentity()然后调用该对象的方法AuthenticationService,并返回一个boolean.
  • boolean然后返回。

想象一下将代码分成两部分:

// Get AuthenticationService object     Call a method of that object
$this->getAuthService()                 ->hasIdentity();

希望有帮助!

于 2012-11-25T18:57:01.817 回答
0

Zend Framework 中的各种插件都是由插件管理器管理的,插件管理器是AbstractPluginManager 的子类,AbstractPluginManager 是ServiceManager 的子类。

$this->zfcUserAuthentication()AbstractController 在内部代理到 pluginmanager。

AuthenticationService::hasIdentity()检查在此请求或先前请求的成功身份验证尝试期间是否将某些内容添加到存储中: 请参阅此处

于 2012-11-25T19:01:42.693 回答