调用php类函数语法

时间:2012-11-25 18:06:09

标签: php class controller zend-framework2 zend-controller-plugin

我目前正在从Zend 2的ZfcUser模块中查看这段代码:

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()。我不熟悉函数调用的这种类型的高级类实现,所以我真的很感激这里的任何解释或我应该研究的主题。

2 个答案:

答案 0 :(得分:1)

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

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

因此有两种不同的hasIdentity()方法:

  • AuthenticationService班级(source code here)。
  • 在您正在查看的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();

希望有所帮助!

答案 1 :(得分:0)

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

$this->zfcUserAuthentication()代理由AbstractController内部的pluginmanager。

AuthenticationService::hasIdentity()检查在此请求或上一个请求中成功进行身份验证尝试时是否已将某些内容添加到存储中: See here