這段代碼是ZF2,但是這樣的感覺就像它可能是一個更普通的OOP問題,因爲它關於接口的一些混淆。這個例子有點長,但我想用我所有的代碼來展示我正在做的一切。PHP OOP:困惑一種返回接口的方法
因此,這裏的代碼段是我混亂的根源:
// 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一些PARAMS第一種方法,將它傳遞給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方法?
對不起,如果這個問題令人困惑,讀我很困惑這裏發生了什麼在一個非常基本的水平,所以它很難讓我更清醒。
好吧,我想我明白了。它返回的對象必須實現接口。但是我仍然感到困惑 - 需要_returned_來實現接口的優點是什麼?除了要求傳遞給setAdapter()的對象來實現接口之外,您不必再進行任何操作,因爲此時您將知道getAdapter()檢索到的任何適配器都必須實現它。看起來多餘。 – red888
這就是所謂的「策略」模式(可能也可以在不同的名字下找到)。它基本上允許身份驗證服務與AdapterInterfaces的不同實現一起工作,除了在接口中定義的幾個特殊情況函數外,無需知道其實現上的任何內容。更多信息:http://www.phptherightway.com/pages/Design-Patterns.html(最後) – phoops
信息來自DocBlock:https://github.com/zendframework/zf2/blob/master/library /Zend/Authentication/AuthenticationService.php#L49。這不是要求,它只是文檔 - 它幫助像IDEs這樣的東西知道,如果某些代碼調用' - > getAdapter()',返回什麼樣的對象 –