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