我在使用驗證在ZF2:AuthController在另一個模塊
這是一個控制器
<?php
namespace Admin\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\View\Model\ViewModel;
use Admin\Model\User;
class AuthController extends AbstractActionController {
protected $form;
protected $storage;
protected $authservice;
public function getAuthService() {
if (!$this->authservice) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
public function getSessionStorage() {
if (!$this->storage) {
$this->storage = $this->getServiceLocator()->get('Admin\Model\MyAuthStorage');
}
return $this->storage;
}
public function getForm() {
if (!$this->form) {
$user = new User();
$builder = new AnnotationBuilder();
$this->form = $builder->createForm($user);
}
return $this->form;
}
public function loginAction() {
//if already login, redirect to success page
if ($this->getAuthService()->hasIdentity()) {
return $this->redirect()->toRoute('success');
}
$form = $this->getForm();
return array(
'form' => $form,
'messages' => $this->flashmessenger()->getMessages()
);
}
public function authenticateAction() {
$form = $this->getForm();
$redirect = 'login';
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
//check authentication...
$this->getAuthService()->getAdapter()
->setIdentity($request->getPost('username'))
->setCredential($request->getPost('password'));
$result = $this->getAuthService()->authenticate();
foreach ($result->getMessages() as $message) {
//save message temporary into flashmessenger
$this->flashmessenger()->addMessage($message);
}
if ($result->isValid()) {
$redirect = 'success';
//check if it has rememberMe :
if ($request->getPost('rememberme') == 1) {
$this->getSessionStorage()
->setRememberMe(1);
//set storage again
$this->getAuthService()->setStorage($this->getSessionStorage());
}
$this->getAuthService()->setStorage($this->getSessionStorage());
$this->getAuthService()->getStorage()->write($request->getPost('username'));
}
}
}
return $this->redirect()->toRoute($redirect);
}
public function logoutAction() {
if ($this->getAuthService()->hasIdentity()) {
$this->getSessionStorage()->forgetMe();
$this->getAuthService()->clearIdentity();
$this->flashmessenger()->addMessage("Logout done.");
}
return $this->redirect()->toRoute('login');
}
}
當我嘗試使用此控制器在另一個模塊中「信息例如」它返回一個錯誤消息:
使用
use Admin\Controller\AuthController;
public function indexAction() {
$getAuth = new AuthController();
$getAuth->getServiceLocator()->get('AuthService')->hasIdentity();
$authService = $getAuth->getAuthService();
if ($authService->hasIdentity()) {
echo 'Auth area';
}
}
錯誤消息回報是:
Fatal error: Call to a member function get() on a non-object in .....\Controller\PostsController.php on line 31
Line 31 mean: $getAuth->getServiceLocator()->get('AuthService')->hasIdentity();
什麼問題?
在控制器中使用'getServiceLocator()'是非常糟糕的做法。不要這樣做。將依賴注入到控制器中,不要從控制器內的服務管理器中獲取它們。 – Tomdarkness