PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/DevApp/library/Zend/Controller/Action.php

http://firephp.googlecode.com/
PHP | 669 lines | 255 code | 67 blank | 347 comment | 38 complexity | 534f07e4e6e5e52a466af7af2d0156a3 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, MIT, Apache-2.0
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Controller
  17. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /** Zend_Controller_Action_HelperBroker */
  21. require_once 'Zend/Controller/Action/HelperBroker.php';
  22. /** Zend_Controller_Front */
  23. require_once 'Zend/Controller/Front.php';
  24. /**
  25. * @category Zend
  26. * @package Zend_Controller
  27. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  28. * @license http://framework.zend.com/license/new-bsd New BSD License
  29. */
  30. abstract class Zend_Controller_Action
  31. {
  32. /**
  33. * Word delimiters (used for normalizing view script paths)
  34. * @var array
  35. */
  36. protected $_delimiters;
  37. /**
  38. * Array of arguments provided to the constructor, minus the
  39. * {@link $_request Request object}.
  40. * @var array
  41. */
  42. protected $_invokeArgs = array();
  43. /**
  44. * Front controller instance
  45. * @var Zend_Controller_Front
  46. */
  47. protected $_frontController;
  48. /**
  49. * Zend_Controller_Request_Abstract object wrapping the request environment
  50. * @var Zend_Controller_Request_Abstract
  51. */
  52. protected $_request = null;
  53. /**
  54. * Zend_Controller_Response_Abstract object wrapping the response
  55. * @var Zend_Controller_Response_Abstract
  56. */
  57. protected $_response = null;
  58. /**
  59. * View script suffix; defaults to 'phtml'
  60. * @see {render()}
  61. * @var string
  62. */
  63. public $viewSuffix = 'phtml';
  64. /**
  65. * View object
  66. * @var Zend_View_Interface
  67. */
  68. public $view;
  69. /**
  70. * Helper Broker to assist in routing help requests to the proper object
  71. *
  72. * @var Zend_Controller_Action_HelperBroker
  73. */
  74. protected $_helper = null;
  75. /**
  76. * Class constructor
  77. *
  78. * The request and response objects should be registered with the
  79. * controller, as should be any additional optional arguments; these will be
  80. * available via {@link getRequest()}, {@link getResponse()}, and
  81. * {@link getInvokeArgs()}, respectively.
  82. *
  83. * When overriding the constructor, please consider this usage as a best
  84. * practice and ensure that each is registered appropriately; the easiest
  85. * way to do so is to simply call parent::__construct($request, $response,
  86. * $invokeArgs).
  87. *
  88. * After the request, response, and invokeArgs are set, the
  89. * {@link $_helper helper broker} is initialized.
  90. *
  91. * Finally, {@link init()} is called as the final action of
  92. * instantiation, and may be safely overridden to perform initialization
  93. * tasks; as a general rule, override {@link init()} instead of the
  94. * constructor to customize an action controller's instantiation.
  95. *
  96. * @param Zend_Controller_Request_Abstract $request
  97. * @param Zend_Controller_Response_Abstract $response
  98. * @param array $invokeArgs Any additional invocation arguments
  99. * @return void
  100. */
  101. public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
  102. {
  103. $this->setRequest($request)
  104. ->setResponse($response)
  105. ->_setInvokeArgs($invokeArgs);
  106. $this->_helper = new Zend_Controller_Action_HelperBroker($this);
  107. $this->init();
  108. }
  109. /**
  110. * Initialize object
  111. *
  112. * Called from {@link __construct()} as final step of object instantiation.
  113. *
  114. * @return void
  115. */
  116. public function init()
  117. {
  118. }
  119. /**
  120. * Initialize View object
  121. *
  122. * Initializes {@link $view} if not otherwise a Zend_View_Interface.
  123. *
  124. * If {@link $view} is not otherwise set, instantiates a new Zend_View
  125. * object, using the 'views' subdirectory at the same level as the
  126. * controller directory for the current module as the base directory.
  127. * It uses this to set the following:
  128. * - script path = views/scripts/
  129. * - helper path = views/helpers/
  130. * - filter path = views/filters/
  131. *
  132. * @return Zend_View_Interface
  133. * @throws Zend_Controller_Exception if base view directory does not exist
  134. */
  135. public function initView()
  136. {
  137. if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
  138. return $this->view;
  139. }
  140. require_once 'Zend/View/Interface.php';
  141. if (isset($this->view) && ($this->view instanceof Zend_View_Interface)) {
  142. return $this->view;
  143. }
  144. $request = $this->getRequest();
  145. $module = $request->getModuleName();
  146. $dirs = $this->getFrontController()->getControllerDirectory();
  147. if (empty($module) || !isset($dirs[$module])) {
  148. $module = $this->getFrontController()->getDispatcher()->getDefaultModule();
  149. }
  150. $baseDir = dirname($dirs[$module]) . DIRECTORY_SEPARATOR . 'views';
  151. if (!file_exists($baseDir) || !is_dir($baseDir)) {
  152. require_once 'Zend/Controller/Exception.php';
  153. throw new Zend_Controller_Exception('Missing base view directory ("' . $baseDir . '")');
  154. }
  155. require_once 'Zend/View.php';
  156. $this->view = new Zend_View(array('basePath' => $baseDir));
  157. return $this->view;
  158. }
  159. /**
  160. * Render a view
  161. *
  162. * Renders a view. By default, views are found in the view script path as
  163. * <controller>/<action>.phtml. You may change the script suffix by
  164. * resetting {@link $viewSuffix}. You may omit the controller directory
  165. * prefix by specifying boolean true for $noController.
  166. *
  167. * By default, the rendered contents are appended to the response. You may
  168. * specify the named body content segment to set by specifying a $name.
  169. *
  170. * @see Zend_Controller_Response_Abstract::appendBody()
  171. * @param string|null $action Defaults to action registered in request object
  172. * @param string|null $name Response object named path segment to use; defaults to null
  173. * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script
  174. * @return void
  175. */
  176. public function render($action = null, $name = null, $noController = false)
  177. {
  178. if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
  179. return $this->_helper->viewRenderer->render($action, $name, $noController);
  180. }
  181. $view = $this->initView();
  182. $script = $this->getViewScript($action, $noController);
  183. $this->getResponse()->appendBody(
  184. $view->render($script),
  185. $name
  186. );
  187. }
  188. /**
  189. * Render a given view script
  190. *
  191. * Similar to {@link render()}, this method renders a view script. Unlike render(),
  192. * however, it does not autodetermine the view script via {@link getViewScript()},
  193. * but instead renders the script passed to it. Use this if you know the
  194. * exact view script name and path you wish to use, or if using paths that do not
  195. * conform to the spec defined with getViewScript().
  196. *
  197. * By default, the rendered contents are appended to the response. You may
  198. * specify the named body content segment to set by specifying a $name.
  199. *
  200. * @param string $script
  201. * @param string $name
  202. * @return void
  203. */
  204. public function renderScript($script, $name = null)
  205. {
  206. if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
  207. return $this->_helper->viewRenderer->renderScript($script, $name);
  208. }
  209. $view = $this->initView();
  210. $this->getResponse()->appendBody(
  211. $view->render($script),
  212. $name
  213. );
  214. }
  215. /**
  216. * Construct view script path
  217. *
  218. * Used by render() to determine the path to the view script.
  219. *
  220. * @param string $action Defaults to action registered in request object
  221. * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script
  222. * @return string
  223. * @throws Zend_Controller_Exception with bad $action
  224. */
  225. public function getViewScript($action = null, $noController = null)
  226. {
  227. if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
  228. $viewRenderer = $this->_helper->getHelper('viewRenderer');
  229. if (null !== $noController) {
  230. $viewRenderer->setNoController($noController);
  231. }
  232. return $viewRenderer->getViewScript($action);
  233. }
  234. $request = $this->getRequest();
  235. if (null === $action) {
  236. $action = $request->getActionName();
  237. } elseif (!is_string($action)) {
  238. require_once 'Zend/Controller/Exception.php';
  239. throw new Zend_Controller_Exception('Invalid action specifier for view render');
  240. }
  241. if (null === $this->_delimiters) {
  242. $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
  243. $wordDelimiters = $dispatcher->getWordDelimiter();
  244. $pathDelimiters = $dispatcher->getPathDelimiter();
  245. $this->_delimiters = array_unique(array_merge($wordDelimiters, (array) $pathDelimiters));
  246. }
  247. $action = str_replace($this->_delimiters, '-', $action);
  248. $script = $action . '.' . $this->viewSuffix;
  249. if (!$noController) {
  250. $controller = $request->getControllerName();
  251. $controller = str_replace($this->_delimiters, '-', $controller);
  252. $script = $controller . DIRECTORY_SEPARATOR . $script;
  253. }
  254. return $script;
  255. }
  256. /**
  257. * Return the Request object
  258. *
  259. * @return Zend_Controller_Request_Abstract
  260. */
  261. public function getRequest()
  262. {
  263. return $this->_request;
  264. }
  265. /**
  266. * Set the Request object
  267. *
  268. * @param Zend_Controller_Request_Abstract $request
  269. * @return Zend_Controller_Action
  270. */
  271. public function setRequest(Zend_Controller_Request_Abstract $request)
  272. {
  273. $this->_request = $request;
  274. return $this;
  275. }
  276. /**
  277. * Return the Response object
  278. *
  279. * @return Zend_Controller_Response_Abstract
  280. */
  281. public function getResponse()
  282. {
  283. return $this->_response;
  284. }
  285. /**
  286. * Set the Response object
  287. *
  288. * @param Zend_Controller_Response_Abstract $response
  289. * @return Zend_Controller_Action
  290. */
  291. public function setResponse(Zend_Controller_Response_Abstract $response)
  292. {
  293. $this->_response = $response;
  294. return $this;
  295. }
  296. /**
  297. * Set invocation arguments
  298. *
  299. * @param array $args
  300. * @return Zend_Controller_Action
  301. */
  302. protected function _setInvokeArgs(array $args = array())
  303. {
  304. $this->_invokeArgs = $args;
  305. return $this;
  306. }
  307. /**
  308. * Return the array of constructor arguments (minus the Request object)
  309. *
  310. * @return array
  311. */
  312. public function getInvokeArgs()
  313. {
  314. return $this->_invokeArgs;
  315. }
  316. /**
  317. * Return a single invocation argument
  318. *
  319. * @param string $key
  320. * @return mixed
  321. */
  322. public function getInvokeArg($key)
  323. {
  324. if (isset($this->_invokeArgs[$key])) {
  325. return $this->_invokeArgs[$key];
  326. }
  327. return null;
  328. }
  329. /**
  330. * Get a helper by name
  331. *
  332. * @param string $helperName
  333. * @return Zend_Controller_Action_Helper_Abstract
  334. */
  335. public function getHelper($helperName)
  336. {
  337. return $this->_helper->{$helperName};
  338. }
  339. /**
  340. * Get a clone of a helper by name
  341. *
  342. * @param string $helperName
  343. * @return Zend_Controller_Action_Helper_Abstract
  344. */
  345. public function getHelperCopy($helperName)
  346. {
  347. return clone $this->_helper->{$helperName};
  348. }
  349. /**
  350. * Set the front controller instance
  351. *
  352. * @param Zend_Controller_Front $front
  353. * @return Zend_Controller_Action
  354. */
  355. public function setFrontController(Zend_Controller_Front $front)
  356. {
  357. $this->_frontController = $front;
  358. return $this;
  359. }
  360. /**
  361. * Retrieve Front Controller
  362. *
  363. * @return Zend_Controller_Front
  364. */
  365. public function getFrontController()
  366. {
  367. // Used cache version if found
  368. if (null !== $this->_frontController) {
  369. return $this->_frontController;
  370. }
  371. // Grab singleton instance, if class has been loaded
  372. if (class_exists('Zend_Controller_Front')) {
  373. $this->_frontController = Zend_Controller_Front::getInstance();
  374. return $this->_frontController;
  375. }
  376. // Throw exception in all other cases
  377. require_once 'Zend/Controller/Exception.php';
  378. throw new Zend_Controller_Exception('Front controller class has not been loaded');
  379. }
  380. /**
  381. * Pre-dispatch routines
  382. *
  383. * Called before action method. If using class with
  384. * {@link Zend_Controller_Front}, it may modify the
  385. * {@link $_request Request object} and reset its dispatched flag in order
  386. * to skip processing the current action.
  387. *
  388. * @return void
  389. */
  390. public function preDispatch()
  391. {
  392. }
  393. /**
  394. * Post-dispatch routines
  395. *
  396. * Called after action method execution. If using class with
  397. * {@link Zend_Controller_Front}, it may modify the
  398. * {@link $_request Request object} and reset its dispatched flag in order
  399. * to process an additional action.
  400. *
  401. * Common usages for postDispatch() include rendering content in a sitewide
  402. * template, link url correction, setting headers, etc.
  403. *
  404. * @return void
  405. */
  406. public function postDispatch()
  407. {
  408. }
  409. /**
  410. * Proxy for undefined methods. Default behavior is to throw an
  411. * exception on undefined methods, however this function can be
  412. * overridden to implement magic (dynamic) actions, or provide run-time
  413. * dispatching.
  414. *
  415. * @param string $methodName
  416. * @param array $args
  417. */
  418. public function __call($methodName, $args)
  419. {
  420. if ('Action' == substr($methodName, -6)) {
  421. require_once 'Zend/Controller/Action/Exception.php';
  422. $action = substr($methodName, 0, strlen($methodName) - 6);
  423. require_once 'Zend/Controller/Action/Exception.php';
  424. throw new Zend_Controller_Action_Exception(sprintf('Action "%s" does not exist and was not trapped in __call()', $action), 404);
  425. }
  426. require_once 'Zend/Controller/Action/Exception.php';
  427. throw new Zend_Controller_Action_Exception(sprintf('Method "%s" does not exist and was not trapped in __call()', $methodName), 500);
  428. }
  429. /**
  430. * Dispatch the requested action
  431. *
  432. * @param string $action Method name of action
  433. * @return void
  434. */
  435. public function dispatch($action)
  436. {
  437. // Notify helpers of action preDispatch state
  438. $this->_helper->notifyPreDispatch();
  439. $this->preDispatch();
  440. if ($this->getRequest()->isDispatched()) {
  441. // preDispatch() didn't change the action, so we can continue
  442. if ($this->getInvokeArg('useCaseSensitiveActions') || in_array($action, get_class_methods($this))) {
  443. if ($this->getInvokeArg('useCaseSensitiveActions')) {
  444. trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this "feature"');
  445. }
  446. $this->$action();
  447. } else {
  448. $this->__call($action, array());
  449. }
  450. $this->postDispatch();
  451. }
  452. // whats actually important here is that this action controller is
  453. // shutting down, regardless of dispatching; notify the helpers of this
  454. // state
  455. $this->_helper->notifyPostDispatch();
  456. }
  457. /**
  458. * Call the action specified in the request object, and return a response
  459. *
  460. * Not used in the Action Controller implementation, but left for usage in
  461. * Page Controller implementations. Dispatches a method based on the
  462. * request.
  463. *
  464. * Returns a Zend_Controller_Response_Abstract object, instantiating one
  465. * prior to execution if none exists in the controller.
  466. *
  467. * {@link preDispatch()} is called prior to the action,
  468. * {@link postDispatch()} is called following it.
  469. *
  470. * @param null|Zend_Controller_Request_Abstract $request Optional request
  471. * object to use
  472. * @param null|Zend_Controller_Response_Abstract $response Optional response
  473. * object to use
  474. * @return Zend_Controller_Response_Abstract
  475. */
  476. public function run(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null)
  477. {
  478. if (null !== $request) {
  479. $this->setRequest($request);
  480. } else {
  481. $request = $this->getRequest();
  482. }
  483. if (null !== $response) {
  484. $this->setResponse($response);
  485. }
  486. $action = $request->getActionName();
  487. if (empty($action)) {
  488. $action = 'index';
  489. }
  490. $action = $action . 'Action';
  491. $request->setDispatched(true);
  492. $this->dispatch($action);
  493. return $this->getResponse();
  494. }
  495. /**
  496. * Gets a parameter from the {@link $_request Request object}. If the
  497. * parameter does not exist, NULL will be returned.
  498. *
  499. * If the parameter does not exist and $default is set, then
  500. * $default will be returned instead of NULL.
  501. *
  502. * @param string $paramName
  503. * @param mixed $default
  504. * @return mixed
  505. */
  506. final protected function _getParam($paramName, $default = null)
  507. {
  508. $value = $this->getRequest()->getParam($paramName);
  509. if ((null == $value) && (null !== $default)) {
  510. $value = $default;
  511. }
  512. return $value;
  513. }
  514. /**
  515. * Set a parameter in the {@link $_request Request object}.
  516. *
  517. * @param string $paramName
  518. * @param mixed $value
  519. * @return Zend_Controller_Action
  520. */
  521. final protected function _setParam($paramName, $value)
  522. {
  523. $this->getRequest()->setParam($paramName, $value);
  524. return $this;
  525. }
  526. /**
  527. * Determine whether a given parameter exists in the
  528. * {@link $_request Request object}.
  529. *
  530. * @param string $paramName
  531. * @return boolean
  532. */
  533. final protected function _hasParam($paramName)
  534. {
  535. return null !== $this->getRequest()->getParam($paramName);
  536. }
  537. /**
  538. * Return all parameters in the {@link $_request Request object}
  539. * as an associative array.
  540. *
  541. * @return array
  542. */
  543. final protected function _getAllParams()
  544. {
  545. return $this->getRequest()->getParams();
  546. }
  547. /**
  548. * Forward to another controller/action.
  549. *
  550. * It is important to supply the unformatted names, i.e. "article"
  551. * rather than "ArticleController". The dispatcher will do the
  552. * appropriate formatting when the request is received.
  553. *
  554. * If only an action name is provided, forwards to that action in this
  555. * controller.
  556. *
  557. * If an action and controller are specified, forwards to that action and
  558. * controller in this module.
  559. *
  560. * Specifying an action, controller, and module is the most specific way to
  561. * forward.
  562. *
  563. * A fourth argument, $params, will be used to set the request parameters.
  564. * If either the controller or module are unnecessary for forwarding,
  565. * simply pass null values for them before specifying the parameters.
  566. *
  567. * @param string $action
  568. * @param string $controller
  569. * @param string $module
  570. * @param array $params
  571. * @return void
  572. */
  573. final protected function _forward($action, $controller = null, $module = null, array $params = null)
  574. {
  575. $request = $this->getRequest();
  576. if (null !== $params) {
  577. $request->setParams($params);
  578. }
  579. if (null !== $controller) {
  580. $request->setControllerName($controller);
  581. // Module should only be reset if controller has been specified
  582. if (null !== $module) {
  583. $request->setModuleName($module);
  584. }
  585. }
  586. $request->setActionName($action)
  587. ->setDispatched(false);
  588. }
  589. /**
  590. * Redirect to another URL
  591. *
  592. * Proxies to {@link Zend_Controller_Action_Helper_Redirector::gotoUrl()}.
  593. *
  594. * @param string $url
  595. * @param array $options Options to be used when redirecting
  596. * @return void
  597. */
  598. protected function _redirect($url, array $options = array())
  599. {
  600. $this->_helper->redirector->gotoUrl($url, $options);
  601. }
  602. }