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:         // check HTTP method
  81. 81:         if ($this->allowedMethods{
  82. 82:             $method $httpRequest->getMethod();
  83. 83:             if (!in_array($method$this->allowedMethodsTRUE)) {
  84. 84:                 $httpResponse->setCode(IHttpResponse::S501_NOT_IMPLEMENTED);
  85. 85:                 $httpResponse->setHeader('Allow'implode(','$this->allowedMethods));
  86. 86:                 echo '<h1>Method ' htmlSpecialChars($method' is not implemented</h1>';
  87. 87:                 return;
  88. 88:             }
  89. 89:         }
  90. 90:  
  91. 91:         // dispatching
  92. 92:         $request NULL;
  93. 93:         $repeatedError FALSE;
  94. 94:         do {
  95. 95:             try {
  96. 96:                 if (count($this->requestsself::$maxLoop{
  97. 97:                     throw new ApplicationException('Too many loops detected in application life cycle.');
  98. 98:                 }
  99. 99:  
  100. 100:                 if (!$request{
  101. 101:                     $this->onStartup($this);
  102. 102:  
  103. 103:                     // default router
  104. 104:                     $router $this->getRouter();
  105. 105:                     if ($router instanceof MultiRouter && !count($router)) {
  106. 106:                         $router[new SimpleRouter(array(
  107. 107:                             'presenter' => 'Default',
  108. 108:                             'action' => 'default',
  109. 109:                         ));
  110. 110:                     }
  111. 111:  
  112. 112:                     // routing
  113. 113:                     $request $router->match($httpRequest);
  114. 114:                     if (!($request instanceof PresenterRequest)) {
  115. 115:                         $request NULL;
  116. 116:                         throw new BadRequestException('No route for HTTP request.');
  117. 117:                     }
  118. 118:  
  119. 119:                     if (strcasecmp($request->getPresenterName()$this->errorPresenter=== 0{
  120. 120:                         throw new BadRequestException('Invalid request.');
  121. 121:                     }
  122. 122:                 }
  123. 123:  
  124. 124:                 $this->requests[$request;
  125. 125:                 $this->onRequest($this$request);
  126. 126:  
  127. 127:                 // Instantiate presenter
  128. 128:                 $presenter $request->getPresenterName();
  129. 129:                 try {
  130. 130:                     $class $this->getPresenterLoader()->getPresenterClass($presenter);
  131. 131:                     $request->setPresenterName($presenter);
  132. 132:                 catch (InvalidPresenterException $e{
  133. 133:                     throw new BadRequestException($e->getMessage()404$e);
  134. 134:                 }
  135. 135:                 $request->freeze();
  136. 136:  
  137. 137:                 // Execute presenter
  138. 138:                 $this->presenter new $class;
  139. 139:                 $response $this->presenter->run($request);
  140. 140:  
  141. 141:                 // Send response
  142. 142:                 if ($response instanceof ForwardingResponse{
  143. 143:                     $request $response->getRequest();
  144. 144:                     continue;
  145. 145:  
  146. 146:                 elseif ($response instanceof IPresenterResponse{
  147. 147:                     $response->send();
  148. 148:                 }
  149. 149:                 break;
  150. 150:  
  151. 151:             catch (Exception $e{
  152. 152:                 // fault barrier
  153. 153:                 if ($this->catchExceptions === NULL{
  154. 154:                     $this->catchExceptions = Environment::isProduction();
  155. 155:                 }
  156. 156:  
  157. 157:                 if (!$this->catchExceptions{
  158. 158:                     throw $e;
  159. 159:                 }
  160. 160:  
  161. 161:                 $this->onError($this$e);
  162. 162:  
  163. 163:                 if ($repeatedError{
  164. 164:                     $e new ApplicationException('An error occured while executing error-presenter'0$e);
  165. 165:                 }
  166. 166:  
  167. 167:                 if (!$httpResponse->isSent()) {
  168. 168:                     $httpResponse->setCode($e instanceof BadRequestException $e->getCode(500);
  169. 169:                 }
  170. 170:  
  171. 171:                 if (!$repeatedError && $this->errorPresenter{
  172. 172:                     $repeatedError TRUE;
  173. 173:                     $request new PresenterRequest(
  174. 174:                         $this->errorPresenter,
  175. 175:                         PresenterRequest::FORWARD,
  176. 176:                         array('exception' => $e)
  177. 177:                     );
  178. 178:                     // continue
  179. 179:  
  180. 180:                 else // default error handler
  181. 181:                     echo "<meta name='robots' content='noindex'>\n\n";
  182. 182:                     if ($e instanceof BadRequestException{
  183. 183:                         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>";
  184. 184:  
  185. 185:                     else {
  186. 186:                         Debug::processException($eFALSE);
  187. 187:                         echo "<title>500 Internal Server Error</title>\n\n<h1>Server Error</h1>\n\n",
  188. 188:                             "<p>The server encountered an internal error and was unable to complete your request. Please try again later.</p>";
  189. 189:                     }
  190. 190:                     echo "\n\n<hr>\n<small><i>Nette Framework</i></small>";
  191. 191:                     break;
  192. 192:                 }
  193. 193:             }
  194. 194:         while (1);
  195. 195:  
  196. 196:         $this->onShutdown($thisisset($e$e NULL);
  197. 197:     }
  198. 198:  
  199. 199:  
  200. 200:  
  201. 201:     /**
  202. 202:      * Returns all processed requests.
  203. 203:      * @return array of PresenterRequest
  204. 204:      */
  205. 205:     final public function getRequests()
  206. 206:     {
  207. 207:         return $this->requests;
  208. 208:     }
  209. 209:  
  210. 210:  
  211. 211:  
  212. 212:     /**
  213. 213:      * Returns current presenter.
  214. 214:      * @return Presenter 
  215. 215:      */
  216. 216:     final public function getPresenter()
  217. 217:     {
  218. 218:         return $this->presenter;
  219. 219:     }
  220. 220:  
  221. 221:  
  222. 222:  
  223. 223:     /********************* services ****************d*g**/
  224. 224:  
  225. 225:  
  226. 226:  
  227. 227:     /**
  228. 228:      * Gets the service locator (experimental).
  229. 229:      * @return IServiceLocator 
  230. 230:      */
  231. 231:     final public function getServiceLocator()
  232. 232:     {
  233. 233:         if ($this->serviceLocator === NULL{
  234. 234:             $this->serviceLocator new ServiceLocator(Environment::getServiceLocator());
  235. 235:  
  236. 236:             foreach ($this->defaultServices as $name => $service{
  237. 237:                 if (!$this->serviceLocator->hasService($name)) {
  238. 238:                     $this->serviceLocator->addService($name$service);
  239. 239:                 }
  240. 240:             }
  241. 241:         }
  242. 242:         return $this->serviceLocator;
  243. 243:     }
  244. 244:  
  245. 245:  
  246. 246:  
  247. 247:     /**
  248. 248:      * Gets the service object of the specified type.
  249. 249:      * @param  string service name
  250. 250:      * @param  array  options in case service is not singleton
  251. 251:      * @return object 
  252. 252:      */
  253. 253:     final public function getService($namearray $options NULL)
  254. 254:     {
  255. 255:         return $this->getServiceLocator()->getService($name$options);
  256. 256:     }
  257. 257:  
  258. 258:  
  259. 259:  
  260. 260:     /**
  261. 261:      * Returns router.
  262. 262:      * @return IRouter 
  263. 263:      */
  264. 264:     public function getRouter()
  265. 265:     {
  266. 266:         return $this->getServiceLocator()->getService('Nette\Application\IRouter');
  267. 267:     }
  268. 268:  
  269. 269:  
  270. 270:  
  271. 271:     /**
  272. 272:      * Changes router.
  273. 273:      * @param  IRouter 
  274. 274:      * @return Application  provides a fluent interface
  275. 275:      */
  276. 276:     public function setRouter(IRouter $router)
  277. 277:     {
  278. 278:         $this->getServiceLocator()->addService('Nette\Application\IRouter'$router);
  279. 279:         return $this;
  280. 280:     }
  281. 281:  
  282. 282:  
  283. 283:  
  284. 284:     /**
  285. 285:      * Returns presenter loader.
  286. 286:      * @return IPresenterLoader 
  287. 287:      */
  288. 288:     public function getPresenterLoader()
  289. 289:     {
  290. 290:         return $this->getServiceLocator()->getService('Nette\Application\IPresenterLoader');
  291. 291:     }
  292. 292:  
  293. 293:  
  294. 294:  
  295. 295:     /********************* service factories ****************d*g**/
  296. 296:  
  297. 297:  
  298. 298:  
  299. 299:     /**
  300. 300:      * @return IPresenterLoader 
  301. 301:      */
  302. 302:     public static function createPresenterLoader()
  303. 303:     {
  304. 304:         return new PresenterLoader(Environment::getVariable('appDir'));
  305. 305:     }
  306. 306:  
  307. 307:  
  308. 308:  
  309. 309:     /********************* request serialization ****************d*g**/
  310. 310:  
  311. 311:  
  312. 312:  
  313. 313:     /**
  314. 314:      * Stores current request to session.
  315. 315:      * @param  mixed  optional expiration time
  316. 316:      * @return string key
  317. 317:      */
  318. 318:     public function storeRequest($expiration '+ 10 minutes')
  319. 319:     {
  320. 320:         $session $this->getSession('Nette.Application/requests');
  321. 321:         do {
  322. 322:             $key substr(md5(lcg_value())04);
  323. 323:         while (isset($session[$key]));
  324. 324:  
  325. 325:         $session[$keyend($this->requests);
  326. 326:         $session->setExpiration($expiration$key);
  327. 327:         return $key;
  328. 328:     }
  329. 329:  
  330. 330:  
  331. 331:  
  332. 332:     /**
  333. 333:      * Restores current request to session.
  334. 334:      * @param  string key
  335. 335:      * @return void 
  336. 336:      */
  337. 337:     public function restoreRequest($key)
  338. 338:     {
  339. 339:         $session $this->getSession('Nette.Application/requests');
  340. 340:         if (isset($session[$key])) {
  341. 341:             $request clone $session[$key];
  342. 342:             unset($session[$key]);
  343. 343:             $request->setFlag(PresenterRequest::RESTOREDTRUE);
  344. 344:             $this->presenter->terminate(new ForwardingResponse($request));
  345. 345:         }
  346. 346:     }
  347. 347:  
  348. 348:  
  349. 349:  
  350. 350:     /********************* backend ****************d*g**/
  351. 351:  
  352. 352:  
  353. 353:  
  354. 354:     /**
  355. 355:      * @return IHttpRequest 
  356. 356:      */
  357. 357:     protected function getHttpRequest()
  358. 358:     {
  359. 359:         return Environment::getHttpRequest();
  360. 360:     }
  361. 361:  
  362. 362:  
  363. 363:  
  364. 364:     /**
  365. 365:      * @return IHttpResponse 
  366. 366:      */
  367. 367:     protected function getHttpResponse()
  368. 368:     {
  369. 369:         return Environment::getHttpResponse();
  370. 370:     }
  371. 371:  
  372. 372:  
  373. 373:  
  374. 374:     /**
  375. 375:      * @return Session 
  376. 376:      */
  377. 377:     protected function getSession($namespace NULL)
  378. 378:     {
  379. 379:         return Environment::getSession($namespace);
  380. 380:     }
  381. 381: