Source for file Application.php

Documentation is available at Application.php

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette Framework
  5. 5:  *
  6. 6:  * @copyright  Copyright (c) 2004, 2010 David Grudl
  7. 7:  * @license    http://nettephp.com/license  Nette license
  8. 8:  * @link       http://nettephp.com
  9. 9:  * @category   Nette
  10. 10:  * @package    Nette\Application
  11. 11:  */
  12. 12:  
  13. 13:  
  14. 14:  
  15. 15: /**
  16. 16:  * Front Controller.
  17. 17:  *
  18. 18:  * @copyright  Copyright (c) 2004, 2010 David Grudl
  19. 19:  * @package    Nette\Application
  20. 20:  */
  21. 21: class Application extends Object
  22. 22: {
  23. 23:     /** @var int */
  24. 24:     public static $maxLoop 20;
  25. 25:  
  26. 26:     /** @var array */
  27. 27:     public $defaultServices = array(
  28. 28:         'Nette\Application\IRouter' => 'Nette\Application\MultiRouter',
  29. 29:         'Nette\Application\IPresenterLoader' => array(__CLASS__'createPresenterLoader'),
  30. 30:     );
  31. 31:  
  32. 32:     /** @var bool enable fault barrier? */
  33. 33:     public $catchExceptions;
  34. 34:  
  35. 35:     /** @var string */
  36. 36:     public $errorPresenter;
  37. 37:  
  38. 38:     /** @var array of function(Application $sender); Occurs before the application loads presenter */
  39. 39:     public $onStartup;
  40. 40:  
  41. 41:     /** @var array of function(Application $sender, \Exception $e = NULL); Occurs before the application shuts down */
  42. 42:     public $onShutdown;
  43. 43:  
  44. 44:     /** @var array of function(Application $sender, PresenterRequest $request); Occurs when a new request is ready for dispatch */
  45. 45:     public $onRequest;
  46. 46:  
  47. 47:     /** @var array of function(Application $sender, \Exception $e); Occurs when an unhandled exception occurs in the application */
  48. 48:     public $onError;
  49. 49:  
  50. 50:     /** @var array of string */
  51. 51:     public $allowedMethods = array('GET''POST''HEAD''PUT''DELETE');
  52. 52:  
  53. 53:     /** @var array of PresenterRequest */
  54. 54:     private $requests array();
  55. 55:  
  56. 56:     /** @var Presenter */
  57. 57:     private $presenter;
  58. 58:  
  59. 59:     /** @var ServiceLocator */
  60. 60:     private $serviceLocator;
  61. 61:  
  62. 62:  
  63. 63:  
  64. 64:     /**
  65. 65:      * Dispatch a HTTP request to a front controller.
  66. 66:      * @return void 
  67. 67:      */
  68. 68:     public function run()
  69. 69:     {
  70. 70:         $httpRequest $this->getHttpRequest();
  71. 71:         $httpResponse $this->getHttpResponse();
  72. 72:  
  73. 73:         $httpRequest->setEncoding('UTF-8');
  74. 74:         $httpResponse->setHeader('X-Powered-By''Nette Framework');
  75. 75:  
  76. 76:         if (Environment::getVariable('baseUri'=== NULL{
  77. 77:             Environment::setVariable('baseUri'$httpRequest->getUri()->getBasePath());
  78. 78:         }
  79. 79:  
  80. 80:         // autostarts session
  81. 81:         $session $this->getSession();
  82. 82:         if (!$session->isStarted(&& $session->exists()) {
  83. 83:             $session->start();
  84. 84:         }
  85. 85:  
  86. 86:         // check HTTP method
  87. 87:         if ($this->allowedMethods{
  88. 88:             $method $httpRequest->getMethod();
  89. 89:             if (!in_array($method$this->allowedMethodsTRUE)) {
  90. 90:                 $httpResponse->setCode(IHttpResponse::S501_NOT_IMPLEMENTED);
  91. 91:                 $httpResponse->setHeader('Allow'implode(','$this->allowedMethods));
  92. 92:                 echo '<h1>Method ' htmlSpecialChars($method' is not implemented</h1>';
  93. 93:                 return;
  94. 94:             }
  95. 95:         }
  96. 96:  
  97. 97:         // dispatching
  98. 98:         $request NULL;
  99. 99:         $repeatedError FALSE;
  100. 100:         do {
  101. 101:             try {
  102. 102:                 if (count($this->requestsself::$maxLoop{
  103. 103:                     throw new ApplicationException('Too many loops detected in application life cycle.');
  104. 104:                 }
  105. 105:  
  106. 106:                 if (!$request{
  107. 107:                     $this->onStartup($this);
  108. 108:  
  109. 109:                     // default router
  110. 110:                     $router $this->getRouter();
  111. 111:                     if ($router instanceof MultiRouter && !count($router)) {
  112. 112:                         $router[new SimpleRouter(array(
  113. 113:                             'presenter' => 'Default',
  114. 114:                             'action' => 'default',
  115. 115:                         ));
  116. 116:                     }
  117. 117:  
  118. 118:                     // routing
  119. 119:                     $request $router->match($httpRequest);
  120. 120:                     if (!($request instanceof PresenterRequest)) {
  121. 121:                         $request NULL;
  122. 122:                         throw new BadRequestException('No route for HTTP request.');
  123. 123:                     }
  124. 124:  
  125. 125:                     if (strcasecmp($request->getPresenterName()$this->errorPresenter=== 0{
  126. 126:                         throw new BadRequestException('Invalid request.');
  127. 127:                     }
  128. 128:                 }
  129. 129:  
  130. 130:                 $this->requests[$request;
  131. 131:                 $this->onRequest($this$request);
  132. 132:  
  133. 133:                 // Instantiate presenter
  134. 134:                 $presenter $request->getPresenterName();
  135. 135:                 try {
  136. 136:                     $class $this->getPresenterLoader()->getPresenterClass($presenter);
  137. 137:                     $request->setPresenterName($presenter);
  138. 138:                 catch (InvalidPresenterException $e{
  139. 139:                     throw new BadRequestException($e->getMessage()404$e);
  140. 140:                 }
  141. 141:                 $request->freeze();
  142. 142:  
  143. 143:                 // Execute presenter
  144. 144:                 $this->presenter new $class;
  145. 145:                 $response $this->presenter->run($request);
  146. 146:  
  147. 147:                 // Send response
  148. 148:                 if ($response instanceof ForwardingResponse{
  149. 149:                     $request $response->getRequest();
  150. 150:                     continue;
  151. 151:  
  152. 152:                 elseif ($response instanceof IPresenterResponse{
  153. 153:                     $response->send();
  154. 154:                 }
  155. 155:                 break;
  156. 156:  
  157. 157:             catch (Exception $e{
  158. 158:                 // fault barrier
  159. 159:                 if ($this->catchExceptions === NULL{
  160. 160:                     $this->catchExceptions = Environment::isProduction();
  161. 161:                 }
  162. 162:  
  163. 163:                 if (!$this->catchExceptions{
  164. 164:                     throw $e;
  165. 165:                 }
  166. 166:  
  167. 167:                 $this->onError($this$e);
  168. 168:  
  169. 169:                 if ($repeatedError{
  170. 170:                     $e new ApplicationException('An error occured while executing error-presenter'0$e);
  171. 171:                 }
  172. 172:  
  173. 173:                 if (!$httpResponse->isSent()) {
  174. 174:                     $httpResponse->setCode($e instanceof BadRequestException $e->getCode(500);
  175. 175:                 }
  176. 176:  
  177. 177:                 if (!$repeatedError && $this->errorPresenter{
  178. 178:                     $repeatedError TRUE;
  179. 179:                     $request new PresenterRequest(
  180. 180:                         $this->errorPresenter,
  181. 181:                         PresenterRequest::FORWARD,
  182. 182:                         array('exception' => $e)
  183. 183:                     );
  184. 184:                     // continue
  185. 185:  
  186. 186:                 else // default error handler
  187. 187:                     echo "<meta name='robots' content='noindex'>\n\n";
  188. 188:                     if ($e instanceof BadRequestException{
  189. 189:                         echo "<title>404 Not Found</title>\n\n<h1>Not Found</h1>\n\n<p>The requested URL was not found on this server.</p>";
  190. 190:  
  191. 191:                     else {
  192. 192:                         Debug::processException($eFALSE);
  193. 193:                         echo "<title>500 Internal Server Error</title>\n\n<h1>Server Error</h1>\n\n",
  194. 194:                             "<p>The server encountered an internal error and was unable to complete your request. Please try again later.</p>";
  195. 195:                     }
  196. 196:                     echo "\n\n<hr>\n<small><i>Nette Framework</i></small>";
  197. 197:                     break;
  198. 198:                 }
  199. 199:             }
  200. 200:         while (1);
  201. 201:  
  202. 202:         $this->onShutdown($thisisset($e$e NULL);
  203. 203:     }
  204. 204:  
  205. 205:  
  206. 206:  
  207. 207:     /**
  208. 208:      * Returns all processed requests.
  209. 209:      * @return array of PresenterRequest
  210. 210:      */
  211. 211:     final public function getRequests()
  212. 212:     {
  213. 213:         return $this->requests;
  214. 214:     }
  215. 215:  
  216. 216:  
  217. 217:  
  218. 218:     /**
  219. 219:      * Returns current presenter.
  220. 220:      * @return Presenter 
  221. 221:      */
  222. 222:     final public function getPresenter()
  223. 223:     {
  224. 224:         return $this->presenter;
  225. 225:     }
  226. 226:  
  227. 227:  
  228. 228:  
  229. 229:     /********************* services ****************d*g**/
  230. 230:  
  231. 231:  
  232. 232:  
  233. 233:     /**
  234. 234:      * Gets the service locator (experimental).
  235. 235:      * @return IServiceLocator 
  236. 236:      */
  237. 237:     final public function getServiceLocator()
  238. 238:     {
  239. 239:         if ($this->serviceLocator === NULL{
  240. 240:             $this->serviceLocator new ServiceLocator(Environment::getServiceLocator());
  241. 241:  
  242. 242:             foreach ($this->defaultServices as $name => $service{
  243. 243:                 if (!$this->serviceLocator->hasService($name)) {
  244. 244:                     $this->serviceLocator->addService($name$service);
  245. 245:                 }
  246. 246:             }
  247. 247:         }
  248. 248:         return $this->serviceLocator;
  249. 249:     }
  250. 250:  
  251. 251:  
  252. 252:  
  253. 253:     /**
  254. 254:      * Gets the service object of the specified type.
  255. 255:      * @param  string service name
  256. 256:      * @param  array  options in case service is not singleton
  257. 257:      * @return object 
  258. 258:      */
  259. 259:     final public function getService($namearray $options NULL)
  260. 260:     {
  261. 261:         return $this->getServiceLocator()->getService($name$options);
  262. 262:     }
  263. 263:  
  264. 264:  
  265. 265:  
  266. 266:     /**
  267. 267:      * Returns router.
  268. 268:      * @return IRouter 
  269. 269:      */
  270. 270:     public function getRouter()
  271. 271:     {
  272. 272:         return $this->getServiceLocator()->getService('Nette\Application\IRouter');
  273. 273:     }
  274. 274:  
  275. 275:  
  276. 276:  
  277. 277:     /**
  278. 278:      * Changes router.
  279. 279:      * @param  IRouter 
  280. 280:      * @return Application  provides a fluent interface
  281. 281:      */
  282. 282:     public function setRouter(IRouter $router)
  283. 283:     {
  284. 284:         $this->getServiceLocator()->addService('Nette\Application\IRouter'$router);
  285. 285:         return $this;
  286. 286:     }
  287. 287:  
  288. 288:  
  289. 289:  
  290. 290:     /**
  291. 291:      * Returns presenter loader.
  292. 292:      * @return IPresenterLoader 
  293. 293:      */
  294. 294:     public function getPresenterLoader()
  295. 295:     {
  296. 296:         return $this->getServiceLocator()->getService('Nette\Application\IPresenterLoader');
  297. 297:     }
  298. 298:  
  299. 299:  
  300. 300:  
  301. 301:     /********************* service factories ****************d*g**/
  302. 302:  
  303. 303:  
  304. 304:  
  305. 305:     /**
  306. 306:      * @return IPresenterLoader 
  307. 307:      */
  308. 308:     public static function createPresenterLoader()
  309. 309:     {
  310. 310:         return new PresenterLoader(Environment::getVariable('appDir'));
  311. 311:     }
  312. 312:  
  313. 313:  
  314. 314:  
  315. 315:     /********************* request serialization ****************d*g**/
  316. 316:  
  317. 317:  
  318. 318:  
  319. 319:     /**
  320. 320:      * Stores current request to session.
  321. 321:      * @param  mixed  optional expiration time
  322. 322:      * @return string key
  323. 323:      */
  324. 324:     public function storeRequest($expiration '+ 10 minutes')
  325. 325:     {
  326. 326:         $session $this->getSession('Nette.Application/requests');
  327. 327:         do {
  328. 328:             $key substr(md5(lcg_value())04);
  329. 329:         while (isset($session[$key]));
  330. 330:  
  331. 331:         $session[$keyend($this->requests);
  332. 332:         $session->setExpiration($expiration$key);
  333. 333:         return $key;
  334. 334:     }
  335. 335:  
  336. 336:  
  337. 337:  
  338. 338:     /**
  339. 339:      * Restores current request to session.
  340. 340:      * @param  string key
  341. 341:      * @return void 
  342. 342:      */
  343. 343:     public function restoreRequest($key)
  344. 344:     {
  345. 345:         $session $this->getSession('Nette.Application/requests');
  346. 346:         if (isset($session[$key])) {
  347. 347:             $request clone $session[$key];
  348. 348:             unset($session[$key]);
  349. 349:             $request->setFlag(PresenterRequest::RESTOREDTRUE);
  350. 350:             $this->presenter->terminate(new ForwardingResponse($request));
  351. 351:         }
  352. 352:     }
  353. 353:  
  354. 354:  
  355. 355:  
  356. 356:     /********************* backend ****************d*g**/
  357. 357:  
  358. 358:  
  359. 359:  
  360. 360:     /**
  361. 361:      * @return IHttpRequest 
  362. 362:      */
  363. 363:     protected function getHttpRequest()
  364. 364:     {
  365. 365:         return Environment::getHttpRequest();
  366. 366:     }
  367. 367:  
  368. 368:  
  369. 369:  
  370. 370:     /**
  371. 371:      * @return IHttpResponse 
  372. 372:      */
  373. 373:     protected function getHttpResponse()
  374. 374:     {
  375. 375:         return Environment::getHttpResponse();
  376. 376:     }
  377. 377:  
  378. 378:  
  379. 379:  
  380. 380:     /**
  381. 381:      * @return Session 
  382. 382:      */
  383. 383:     protected function getSession($namespace NULL)
  384. 384:     {
  385. 385:         return Environment::getSession($namespace);
  386. 386:     }
  387. 387: