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: require_once dirname(__FILE__'/../Application/ApplicationException.php';
  25. 25:  
  26. 26:  
  27. 27:  
  28. 28: /**
  29. 29:  * Front Controller.
  30. 30:  *
  31. 31:  * @author     David Grudl
  32. 32:  * @copyright  Copyright (c) 2004, 2009 David Grudl
  33. 33:  * @package    Nette\Application
  34. 34:  */
  35. 35: class Application extends Object
  36. 36: {
  37. 37:     /** @var int */
  38. 38:     public static $maxLoop 20;
  39. 39:  
  40. 40:     /** @var array */
  41. 41:     public $defaultServices = array(
  42. 42:         'Nette\Application\IRouter' => 'Nette\Application\MultiRouter',
  43. 43:         'Nette\Application\IPresenterLoader' => 'Nette\Application\PresenterLoader',
  44. 44:     );
  45. 45:  
  46. 46:     /** @var bool enable fault barrier? */
  47. 47:     public $catchExceptions;
  48. 48:  
  49. 49:     /** @var string */
  50. 50:     public $errorPresenter;
  51. 51:  
  52. 52:     /** @var array of function(Application $sender); Occurs before the application loads presenter */
  53. 53:     public $onStartup;
  54. 54:  
  55. 55:     /** @var array of function(Application $sender, \Exception $e = NULL); Occurs before the application shuts down */
  56. 56:     public $onShutdown;
  57. 57:  
  58. 58:     /** @var array of function(Application $sender, PresenterRequest $request); Occurs when a new request is ready for dispatch */
  59. 59:     public $onRequest;
  60. 60:  
  61. 61:     /** @var array of function(Application $sender, \Exception $e); Occurs when an unhandled exception occurs in the application */
  62. 62:     public $onError;
  63. 63:  
  64. 64:     /** @var array of string */
  65. 65:     public $allowedMethods = array('GET''POST''HEAD');
  66. 66:  
  67. 67:     /** @var array of PresenterRequest */
  68. 68:     private $requests array();
  69. 69:  
  70. 70:     /** @var Presenter */
  71. 71:     private $presenter;
  72. 72:  
  73. 73:     /** @var ServiceLocator */
  74. 74:     private $serviceLocator;
  75. 75:  
  76. 76:  
  77. 77:  
  78. 78:     /**
  79. 79:      * Dispatch a HTTP request to a front controller.
  80. 80:      */
  81. 81:     public function run()
  82. 82:     {
  83. 83:         $httpRequest $this->getHttpRequest();
  84. 84:         $httpResponse $this->getHttpResponse();
  85. 85:  
  86. 86:         $httpRequest->setEncoding('UTF-8');
  87. 87:         $httpResponse->setHeader('X-Powered-By''Nette Framework');
  88. 88:  
  89. 89:         if (Environment::getVariable('baseUri'=== NULL{
  90. 90:             Environment::setVariable('baseUri'$httpRequest->getUri()->getBasePath());
  91. 91:         }
  92. 92:  
  93. 93:         // check HTTP method
  94. 94:         if ($this->allowedMethods{
  95. 95:             $method $httpRequest->getMethod();
  96. 96:             if (!in_array($method$this->allowedMethodsTRUE)) {
  97. 97:                 $httpResponse->setCode(IHttpResponse::S501_NOT_IMPLEMENTED);
  98. 98:                 $httpResponse->setHeader('Allow'implode(','$this->allowedMethods));
  99. 99:                 $method htmlSpecialChars($method);
  100. 100:                 die("<h1>Method $method is not implemented</h1>");
  101. 101:             }
  102. 102:         }
  103. 103:  
  104. 104:         // dispatching
  105. 105:         $request NULL;
  106. 106:         $hasError 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:                 $this->presenter new $class($request);
  150. 150:  
  151. 151:                 // Instantiate topmost service locator
  152. 152:                 $this->presenter->setServiceLocator(new ServiceLocator($this->serviceLocator));
  153. 153:  
  154. 154:                 // Execute presenter
  155. 155:                 $this->presenter->run();
  156. 156:                 break;
  157. 157:  
  158. 158:             catch (RedirectingException $e{
  159. 159:                 // not error, presenter redirects to new URL
  160. 160:                 $httpResponse->redirect($e->getUri()$e->getCode());
  161. 161:                 break;
  162. 162:  
  163. 163:             catch (ForwardingException $e{
  164. 164:                 // not error, presenter forwards to new request
  165. 165:                 $request $e->getRequest();
  166. 166:  
  167. 167:             catch (AbortException $e{
  168. 168:                 // not error, application is correctly terminated
  169. 169:                 unset($e);
  170. 170:                 break;
  171. 171:  
  172. 172:             catch (Exception $e{
  173. 173:                 // fault barrier
  174. 174:                 if ($this->catchExceptions === NULL{
  175. 175:                     $this->catchExceptions = Environment::isProduction();
  176. 176:                 }
  177. 177:  
  178. 178:                 if (!$this->catchExceptions{
  179. 179:                     throw $e;
  180. 180:                 }
  181. 181:  
  182. 182:                 $this->onError($this$e);
  183. 183:  
  184. 184:                 if ($hasError{
  185. 185:                     $e new ApplicationException('An error occured while executing error-presenter'0$e);
  186. 186:  
  187. 187:                 elseif ($this->errorPresenter{
  188. 188:                     $hasError TRUE;
  189. 189:                     $request new PresenterRequest(
  190. 190:                         $this->errorPresenter,
  191. 191:                         PresenterRequest::FORWARD,
  192. 192:                         array('exception' => $e)
  193. 193:                     );
  194. 194:                     continue;
  195. 195:                 }
  196. 196:  
  197. 197:                 if ($e instanceof BadRequestException{
  198. 198:                     if (!$httpResponse->isSent()) {
  199. 199:                         $httpResponse->setCode($e->getCode());
  200. 200:                     }
  201. 201:                     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>";
  202. 202:  
  203. 203:                 else {
  204. 204:                     if (!$httpResponse->isSent()) {
  205. 205:                         $httpResponse->setCode(500);
  206. 206:                     }
  207. 207:                     Debug::processException($eFALSE);
  208. 208:                     echo "<title>500 Internal Server Error</title>\n\n<h1>Server Error</h1>\n\n",
  209. 209:                         "<p>The server encountered an internal error and was unable to complete your request. Please try again later.</p>";
  210. 210:                 }
  211. 211:                 echo "\n\n<hr>\n<small><i>Nette Framework</i></small>";
  212. 212:                 break;
  213. 213:             }
  214. 214:         while (1);
  215. 215:  
  216. 216:         $this->onShutdown($thisisset($e$e NULL);
  217. 217:     }
  218. 218:  
  219. 219:  
  220. 220:  
  221. 221:     /**
  222. 222:      * Returns all processed requests.
  223. 223:      * @return array of PresenterRequest
  224. 224:      */
  225. 225:     final public function getRequests()
  226. 226:     {
  227. 227:         return $this->requests;
  228. 228:     }
  229. 229:  
  230. 230:  
  231. 231:  
  232. 232:     /**
  233. 233:      * Returns current presenter.
  234. 234:      * @return Presenter 
  235. 235:      */
  236. 236:     final public function getPresenter()
  237. 237:     {
  238. 238:         return $this->presenter;
  239. 239:     }
  240. 240:  
  241. 241:  
  242. 242:  
  243. 243:     /********************* services ****************d*g**/
  244. 244:  
  245. 245:  
  246. 246:  
  247. 247:     /**
  248. 248:      * Gets the service locator (experimental).
  249. 249:      * @return IServiceLocator 
  250. 250:      */
  251. 251:     final public function getServiceLocator()
  252. 252:     {
  253. 253:         if ($this->serviceLocator === NULL{
  254. 254:             $this->serviceLocator new ServiceLocator(Environment::getServiceLocator());
  255. 255:  
  256. 256:             foreach ($this->defaultServices as $name => $service{
  257. 257:                 if ($this->serviceLocator->getService($nameFALSE=== NULL{
  258. 258:                     $this->serviceLocator->addService($service$name);
  259. 259:                 }
  260. 260:             }
  261. 261:         }
  262. 262:         return $this->serviceLocator;
  263. 263:     }
  264. 264:  
  265. 265:  
  266. 266:  
  267. 267:     /**
  268. 268:      * Gets the service object of the specified type.
  269. 269:      * @param  string service name
  270. 270:      * @param  bool   throw exception if service doesn't exist?
  271. 271:      * @return mixed 
  272. 272:      */
  273. 273:     final public function getService($name$need TRUE)
  274. 274:     {
  275. 275:         return $this->getServiceLocator()->getService($name$need);
  276. 276:     }
  277. 277:  
  278. 278:  
  279. 279:  
  280. 280:     /**
  281. 281:      * Returns router.
  282. 282:      * @return IRouter 
  283. 283:      */
  284. 284:     public function getRouter()
  285. 285:     {
  286. 286:         return $this->getServiceLocator()->getService('Nette\Application\IRouter');
  287. 287:     }
  288. 288:  
  289. 289:  
  290. 290:  
  291. 291:     /**
  292. 292:      * Changes router.
  293. 293:      * @param  IRouter 
  294. 294:      * @return void 
  295. 295:      */
  296. 296:     public function setRouter(IRouter $router)
  297. 297:     {
  298. 298:         $this->getServiceLocator()->addService($router'Nette\Application\IRouter');
  299. 299:     }
  300. 300:  
  301. 301:  
  302. 302:  
  303. 303:     /**
  304. 304:      * Returns presenter loader.
  305. 305:      * @return IPresenterLoader 
  306. 306:      */
  307. 307:     public function getPresenterLoader()
  308. 308:     {
  309. 309:         return $this->getServiceLocator()->getService('Nette\Application\IPresenterLoader');
  310. 310:     }
  311. 311:  
  312. 312:  
  313. 313:  
  314. 314:     /********************* request serialization ****************d*g**/
  315. 315:  
  316. 316:  
  317. 317:  
  318. 318:     /**
  319. 319:      * Stores current request to session.
  320. 320:      * @param  mixed  optional expiration time
  321. 321:      * @return string key
  322. 322:      */
  323. 323:     public function storeRequest($expiration '+ 10 minutes')
  324. 324:     {
  325. 325:         $session $this->getSession()->getNamespace('Nette.Application/requests');
  326. 326:         do {
  327. 327:             $key substr(md5(lcg_value())04);
  328. 328:         while (isset($session[$key]));
  329. 329:  
  330. 330:         $session[$keyend($this->requests);
  331. 331:         $session->setExpiration($expiration$key);
  332. 332:         return $key;
  333. 333:     }
  334. 334:  
  335. 335:  
  336. 336:  
  337. 337:     /**
  338. 338:      * Restores current request to session.
  339. 339:      * @param  string key
  340. 340:      * @return void 
  341. 341:      */
  342. 342:     public function restoreRequest($key)
  343. 343:     {
  344. 344:         $session $this->getSession()->getNamespace('Nette.Application/requests');
  345. 345:         if (isset($session[$key])) {
  346. 346:             $request clone $session[$key];
  347. 347:             unset($session[$key]);
  348. 348:             $request->setFlag(PresenterRequest::RESTOREDTRUE);
  349. 349:             throw new ForwardingException($request);
  350. 350:         }
  351. 351:     }
  352. 352:  
  353. 353:  
  354. 354:  
  355. 355:     /********************* backend ****************d*g**/
  356. 356:  
  357. 357:  
  358. 358:  
  359. 359:     /**
  360. 360:      * @return IHttpRequest 
  361. 361:      */
  362. 362:     protected function getHttpRequest()
  363. 363:     {
  364. 364:         return Environment::getHttpRequest();
  365. 365:     }
  366. 366:  
  367. 367:  
  368. 368:  
  369. 369:     /**
  370. 370:      * @return IHttpResponse 
  371. 371:      */
  372. 372:     protected function getHttpResponse()
  373. 373:     {
  374. 374:         return Environment::getHttpResponse();
  375. 375:     }
  376. 376:  
  377. 377:  
  378. 378:  
  379. 379:     /**
  380. 380:      * @return Session 
  381. 381:      */
  382. 382:     protected function getSession()
  383. 383:     {
  384. 384:         return Environment::getSession();
  385. 385:     }
  386. 386: