2013-07-17 31 views
0

我尝试使用Zend Framework 2.2,使一个HTTP认证为我的模块中的一个,我的代码是强烈从官方文档的启发,在那里是:的Zend 2.2麻烦HTTP认证

$request=$this->getRequest(); 
    $response=$this->getResponse(); 

    assert($request instanceof Zend\Http\Request); 
    assert($response instanceof Zend\Http\Response); 

的问题是这个断言是错误的,看起来$ request和$ response来自另一个类,所以我的脚本不工作。 如何从我的控制器中获取Zend \ Http \ Request | Response的请求和响应?

非常感谢。

+0

可能的,因为没有一个前导斜杠?尝试\ Zend \ Http \ Request – Andrew

回答

1

如果你想设置一个HTTP认证的整个模块,这里是做什么(至少我是如何做到的):

在Module.php:

public function onBootstrap(MvcEvent $e){ 
     $sharedEvents=$e->getApplication()->getEventManager()->getSharedManager(); 
     $sharedEvents->attach(__NAMESPACE__,MvcEvent::EVENT_DISPATCH, array($this, 'authHttp')); 
    } 


    public function authHttp(MvcEvent $e){ 

     $serviceManager = $e->getApplication()->getServiceManager(); 

     $request=$e->getRequest(); 
     $response=$e->getResponse(); 

     if(!(
      $request instanceof \Zend\Http\Request 
      && $response instanceof \Zend\Http\Response 
     )){ 
      return; // we're not in HTTP context - CLI application? 
      } 

     // Your adapter with config/password etc... 
     $authAdapter=$serviceManager->get('Admin\AuthenticationAdapter'); 

     $authAdapter->setRequest($request); 
     $authAdapter->setResponse($response); 

     $result=$authAdapter->authenticate(); 

     if($result->isValid()){ 
      return true; // everything OK 
     } 

     $response->setContent('Access denied'); 
     $response->setStatusCode(\Zend\Http\Response::STATUS_CODE_401); 

     $e->setResult($response); // short-circuit to application end 

     return false; 
    } 

这是所有:) 。这将适用于模块的任何页面!

+0

谢谢Tounu,它现在工作正常! – stc

+0

如果是解决方案,请不要忘记验证答案;)。很高兴帮助:)。 – Tounu