【发布时间】:2014-04-04 13:54:03
【问题描述】:
这段代码是 ZF2,但感觉它可能是一个更普遍的 OOP 问题,因为它与我对接口的一些混淆有关。这个例子有点啰嗦,但我想用我所有的实际代码来展示我正在做的一切。
所以这里的代码 sn-p 是我困惑的根源:
// References
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
// Class definition
public function getAuthService()
{
if (! $this->authservice) {
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user','email','password', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
$this->authservice = $authService;
}
return $this->authservice;
}
public function processAction()
//
$this->getAuthService()->getAdapter()
->setIdentity($this->request->getPost('email'))
->setCredential($this->request->getPost('password'));
$result = $this->getAuthService()->authenticate();
if ($result->isValid()) {
$this->getAuthService()->getStorage()->write($this->request->getPost('email'));
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'confirm'
));
}
在第一个方法中,我们使用一些参数构造一个新的Zend\Authentication\Adapter\DbTable,将其传递给Zend\Authentication\AuthenticationService 的实例,然后返回该AuthenticationService 的实例。
在下一个方法中,我们调用该方法 ($this->getAuthService()) 来获取 AuthenticationService 的实例,调用 AuthenticationService 的 getAdapter() 方法,然后开始在返回的对象上调用 Zend\Authentication\Adapter\DbTable 方法.
这让我感到困惑。查看定义getAdater()。它实际上并没有返回 Zend\Authentication\Adapter\DbTable 的实例,它只返回一个接口: Zend\Authentication\Adapter\AdapterInterface 并且这个接口没有定义任何 Zend\Authentication\Adapter\DbTable 方法。
所以如果 getAdapter() 只返回一个接口,我怎么能在返回的对象上调用 Zend\Authentication\Adapter\DbTable 方法?
对不起,如果这个问题读起来令人困惑,我对这里发生的事情在一个非常基本的层面上感到困惑,所以我很难更清醒。
【问题讨论】:
标签: php oop interface zend-framework2