Exemplo n.º 1
0
 /**
  * Dispatch an HTTP request to a controller/action.
  *
  * @param Yaf_Request_Abstract|null $request
  *
  * @return void Yaf_Response_Abstract
  */
 public function dispatch()
 {
     $request = $this->getRequest();
     if (!$request instanceof Yaf_Request_Abstract) {
         throw new Yaf_Exception('Expect a Yaf_Request_Abstract instance');
     }
     if ($request instanceof Yaf_Request_Http) {
         $response = new Yaf_Response_Http();
     } elseif ($request instanceof Yaf_Request_Cli) {
         $response = new Yaf_Response_Cli();
     }
     // 选择路由
     $router = $this->getRouter();
     foreach ($this->_plugins as $plugin) {
         $plugin->routerStartup($request, $response);
     }
     $router->route($request);
     $this->_fixDefault($request);
     foreach ($this->_plugins as $plugin) {
         $plugin->routerShutdown($request, $response);
     }
     // 执行Action
     try {
         $view = $this->initView();
         foreach ($this->_plugins as $plugin) {
             $plugin->dispatchLoopStartup($request, $response);
         }
         $nested = Yaf_G::getConf('forward_limit');
         $nested = empty($nested) ? 5 : $nested;
         do {
             foreach ($this->_plugins as $plugin) {
                 $plugin->preDispatch($request, $response, $view);
             }
             $this->handle($request, $response, $view);
             $this->_fixDefault($request);
             foreach ($this->_plugins as $plugin) {
                 $plugin->postDispatch($request, $response);
             }
             $nested--;
         } while (!$request->isDispatched() && $nested > 0);
         foreach ($this->_plugins as $plugin) {
             $plugin->dispatchLoopShutdown($request, $response);
         }
     } catch (Exception $oExp) {
         if (Yaf_G::isDebug() || $request->getMethod() == 'CLI') {
             if ($request->getMethod() == 'CLI') {
                 Yaf_Logger::error(Yaf_G::parseException($oExp));
                 echo Yaf_G::parseException($oExp);
             } else {
                 echo "<pre>";
                 echo Yaf_G::parseException($oExp);
                 echo "</pre>";
             }
         } else {
             $response->setResponseCode(404);
             $view->display('404.phtml');
         }
     }
     if ($nested == 0 && !$request->isDispatched()) {
         throw new Yaf_Exception('The max dispatch nesting ' . Yaf_G::getConf('forward_limit') . ' was reached');
     }
     if ($this->returnResponse() == false) {
         $response->response();
     }
     return $response;
 }