06-Inside-the-Controller-Layer.txt 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. Chapter 6 - Inside The Controller Layer
  2. =======================================
  3. In symfony, the controller layer, which contains the code linking the business logic and the presentation, is split into several components that you use for different purposes:
  4. * The front controller is the unique entry point to the application. It loads the configuration and determines the action to execute.
  5. * Actions contain the applicative logic. They check the integrity of the request and prepare the data needed by the presentation layer.
  6. * The request, response, and session objects give access to the request parameters, the response headers, and the persistent user data. They are used very often in the controller layer.
  7. * Filters are portions of code executed for every request, before or after the action. For example, the security and validation filters are commonly used in web applications. You can extend the framework by creating your own filters.
  8. This chapter describes all these components, but don't be intimidated by their number. For a basic page, you will probably need to write only a few lines in the action class, and that's all. The other controller components will be of use only in specific situations.
  9. The Front Controller
  10. --------------------
  11. All web requests are handled by a single front controller, which is the unique entry point to the whole application in a given environment.
  12. When the front controller receives a request, it uses the routing system to match an action name and a module name with the URL typed (or clicked) by the user. For instance, the following request URL calls the `index.php` script (that's the front controller) and will be understood as a call to the action `myAction` of the module `mymodule`:
  13. http://localhost/index.php/mymodule/myAction
  14. If you are not interested in symfony's internals, that's all that you need to know about the front controller. It is an indispensable component of the symfony MVC architecture, but you will seldom need to change it. So you can jump to the next section unless you really want to know about the guts of the front controller.
  15. ### The Front Controller's Job in Detail
  16. The front controller does the dispatching of the request, but that means a little more than just determining the action to execute. In fact, it executes the code that is common to all actions, including the following:
  17. 1. Load the project configuration class and the symfony libraries.
  18. 2. Create an application configuration and a symfony context.
  19. 3. Load and initiate the core framework classes.
  20. 4. Load the configuration.
  21. 5. Decode the request URL to determine the action to execute and the request parameters.
  22. 6. If the action does not exist, redirect to the 404 error action.
  23. 7. Activate filters (for instance, if the request needs authentication).
  24. 8. Execute the filters, first pass.
  25. 9. Execute the action and render the view.
  26. 10. Execute the filters, second pass.
  27. 11. Output the response.
  28. ### The Default Front Controller
  29. The default front controller, called `index.php` and located in the `web/` directory of the project, is a simple PHP file, as shown in Listing 6-1.
  30. Listing 6-1 - The Default Production Front Controller
  31. [php]
  32. <?php
  33. require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
  34. $configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false);
  35. sfContext::createInstance($configuration)->dispatch();
  36. The front controller includes the application configuration, which takes care of steps 2 through 4. The call to the `dispatch()` method of the `sfController` object (which is the core controller object of the symfony MVC architecture) dispatches the request, taking care of steps 5 through 7. The last steps are handled by the filter chain, as explained later in this chapter.
  37. ### Calling Another Front Controller to Switch the Environment
  38. One front controller exists per environment. As a matter of fact, it is the very existence of a front controller that defines an environment. The environment is defined by the second argument you pass to the `ProjectConfiguration::getApplicationConfiguration()` method call.
  39. To change the environment in which you're browsing your application, just choose another front controller. The default front controllers available when you create a new application with the `generate:app` task are `index.php` for the production environment and `frontend_dev.php` for the development environment (provided that your application is called `frontend`). The default `mod_rewrite` configuration will use `index.php` when the URL doesn't contain a front controller script name. So both of these URLs display the same page (`mymodule/index`) in the production environment:
  40. http://localhost/index.php/mymodule/index
  41. http://localhost/mymodule/index
  42. and this URL displays that same page in the development environment:
  43. http://localhost/frontend_dev.php/mymodule/index
  44. Creating a new environment is as easy as creating a new front controller. For instance, you may need a staging environment to allow your customers to test the application before going to production. To create this staging environment, just copy `web/frontend_dev.php` into `web/frontend_staging.php`, and change the value of the second argument of the `ProjectConfiguration::getApplicationConfiguration()` call to `staging`. Now, in all the configuration files, you can add a new `staging:` section to set specific values for this environment, as shown in Listing 6-2.
  45. Listing 6-2 - Sample `app.yml` with Specific Settings for the Staging Environment
  46. staging:
  47. mail:
  48. webmaster: dummy@mysite.com
  49. contact: dummy@mysite.com
  50. all:
  51. mail:
  52. webmaster: webmaster@mysite.com
  53. contact: contact@mysite.com
  54. If you want to see how the application reacts in this new environment, call the related front controller:
  55. http://localhost/frontend_staging.php/mymodule/index
  56. Actions
  57. -------
  58. The actions are the heart of an application, because they contain all the application's logic. They use the model and define variables for the view. When you make a web request in a symfony application, the URL defines an action and the request parameters.
  59. ### The Action Class
  60. Actions are methods named `executeActionName` of a class named `moduleNameActions` inheriting from the `sfActions` class, and grouped by modules. The action class of a module is stored in an `actions.class.php` file, in the module's `actions/` directory.
  61. Listing 6-3 shows an example of an `actions.class.php` file with only an `index` action for the whole `mymodule` module.
  62. Listing 6-3 - Sample Action Class, in `apps/frontend/modules/mymodule/actions/actions.class.php`
  63. [php]
  64. class mymoduleActions extends sfActions
  65. {
  66. public function executeIndex()
  67. {
  68. // ...
  69. }
  70. }
  71. >**CAUTION**
  72. >Even if method names are not case-sensitive in PHP, they are in symfony. So don't forget that the action methods must start with a lowercase `execute`, followed by the exact action name with the first letter capitalized.
  73. In order to request an action, you need to call the front controller script with the module name and action name as parameters. By default, this is done by appending the couple `module_name`/`action_name` to the script. This means that the action defined in Listing 6-4 can be called by this URL:
  74. http://localhost/index.php/mymodule/index
  75. Adding more actions just means adding more `execute` methods to the `sfActions` object, as shown in Listing 6-4.
  76. Listing 6-4 - Action Class with Two Actions, in `frontend/modules/mymodule/actions/actions.class.php`
  77. [php]
  78. class mymoduleActions extends sfActions
  79. {
  80. public function executeIndex()
  81. {
  82. // ...
  83. }
  84. public function executeList()
  85. {
  86. // ...
  87. }
  88. }
  89. If the size of an action class grows too much, you probably need to do some refactoring and move some code to the model layer. Actions should often be kept short (not more than a few lines), and all the business logic should usually be in the model.
  90. Still, the number of actions in a module can be important enough to lead you to split it in two modules.
  91. >**SIDEBAR**
  92. >Symfony coding standards
  93. >
  94. >In the code examples given in this book, you probably noticed that the opening and closing curly braces (`{` and `}`) occupy one line each. This standard makes the code easier to read.
  95. >
  96. >Among the other coding standards of the framework, indentation is always done by two blank spaces; tabs are not used. This is because tabs have a different space value according to the text editor you use, and because code with mixed tab and blank indentation is impossible to read.
  97. >
  98. >Core and generated symfony PHP files do not end with the usual `?>` closing tag. This is because it is not really needed, and because it can create problems in the output if you ever have blanks after this tag.
  99. >
  100. >And if you really pay attention, you will see that a line never ends with a blank space in symfony. The reason, this time, is more prosaic: lines ending with blanks look ugly in Fabien's text editor.
  101. ### Alternative Action Class Syntax
  102. An alternative action syntax is available to dispatch the actions in separate files, one file per action. In this case, each action class extends `sfAction` (instead of `sfActions`) and is named `actionNameAction`. The actual action method is simply named `execute`. The file name is the same as the class name. This means that the equivalent of Listing 6-4 can be written with the two files shown in Listings 6-5 and 6-6.
  103. Listing 6-5 - Single Action File, in `frontend/modules/mymodule/actions/indexAction.class.php`
  104. [php]
  105. class indexAction extends sfAction
  106. {
  107. public function execute($request)
  108. {
  109. // ...
  110. }
  111. }
  112. Listing 6-6 - Single Action File, in `frontend/modules/mymodule/actions/listAction.class.php`
  113. [php]
  114. class listAction extends sfAction
  115. {
  116. public function execute($request)
  117. {
  118. // ...
  119. }
  120. }
  121. ### Retrieving Information in the Action
  122. The action class offers a way to access controller-related information and the core symfony objects. Listing 6-7 demonstrates how to use them.
  123. Listing 6-7 - `sfActions` Common Methods
  124. [php]
  125. class mymoduleActions extends sfActions
  126. {
  127. public function executeIndex($request)
  128. {
  129. // Retrieving request parameters
  130. $password = $request->getParameter('password');
  131. // Retrieving controller information
  132. $moduleName = $this->getModuleName();
  133. $actionName = $this->getActionName();
  134. // Retrieving framework core objects
  135. $userSession = $this->getUser();
  136. $response = $this->getResponse();
  137. $controller = $this->getController();
  138. $context = $this->getContext();
  139. // Setting action variables to pass information to the template
  140. $this->setVar('foo', 'bar');
  141. $this->foo = 'bar'; // Shorter version
  142. }
  143. }
  144. >**SIDEBAR**
  145. >The context singleton
  146. >
  147. >You already saw, in the front controller, a call to sfContext::createInstance(). In an action, the getContext() method returns the same singleton. It is a very useful object that stores a reference to all the symfony core objects related to a given request, and offers an accessor for each of them:
  148. >
  149. >`sfController`: The controller object (`->getController()`)
  150. >
  151. >`sfRequest`: The request object (`->getRequest()`)
  152. >
  153. >`sfResponse`: The response object (`->getResponse()`)
  154. >
  155. >`sfUser`: The user session object (`->getUser()`)
  156. >
  157. >`sfDatabaseConnection`: The database connection (`->getDatabaseConnection()`)
  158. >
  159. >`sfLogger`: The logger object (`->getLogger()`)
  160. >
  161. >`sfI18N`: The internationalization object (`->getI18N()`)
  162. >
  163. >You can call the `sfContext::getInstance()` singleton from any part of the code.
  164. ### Action Termination
  165. Various behaviors are possible at the conclusion of an action's execution. The value returned by the action method determines how the view will be rendered. Constants of the `sfView` class are used to specify which template is to be used to display the result of the action.
  166. If there is a default view to call (this is the most common case), the action should end as follows:
  167. [php]
  168. return sfView::SUCCESS;
  169. Symfony will then look for a template called `actionNameSuccess.php`. This is defined as the default action behavior, so if you omit the `return` statement in an action method, symfony will also look for an `actionNameSuccess.php` template. Empty actions will also trigger that behavior. See Listing 6-8 for examples of successful action termination.
  170. Listing 6-8 - Actions That Will Call the `indexSuccess.php` and `listSuccess.php` Templates
  171. [php]
  172. public function executeIndex()
  173. {
  174. return sfView::SUCCESS;
  175. }
  176. public function executeList()
  177. {
  178. }
  179. If there is an error view to call, the action should end like this:
  180. [php]
  181. return sfView::ERROR;
  182. Symfony will then look for a template called `actionNameError.php`.
  183. To call a custom view, use this ending:
  184. [php]
  185. return 'MyResult';
  186. Symfony will then look for a template called `actionNameMyResult.php`.
  187. If there is no view to call--for instance, in the case of an action executed in a batch process--the action should end as follows:
  188. [php]
  189. return sfView::NONE;
  190. No template will be executed in that case. It means that you can bypass completely the view layer and set the response HTML code directly from an action. As shown in Listing 6-9, symfony provides a specific `renderText()` method for this case. This can be useful when you need extreme responsiveness of the action, such as for Ajax interactions, which will be discussed in Chapter 11.
  191. Listing 6-9 - Bypassing the View by Echoing the Response and Returning `sfView::NONE`
  192. [php]
  193. public function executeIndex()
  194. {
  195. $this->getResponse()->setContent("<html><body>Hello, World!</body></html>");
  196. return sfView::NONE;
  197. }
  198. // Is equivalent to
  199. public function executeIndex()
  200. {
  201. return $this->renderText("<html><body>Hello, World!</body></html>");
  202. }
  203. In some cases, you need to send an empty response but with some headers defined in it (especially the `X-JSON` header). Define the headers via the `sfResponse` object, discussed in the next chapter, and return the `sfView::HEADER_ONLY` constant, as shown in Listing 6-10.
  204. Listing 6-10 - Escaping View Rendering and Sending Only Headers
  205. [php]
  206. public function executeRefresh()
  207. {
  208. $output = '<"title","My basic letter"],["name","Mr Brown">';
  209. $this->getResponse()->setHttpHeader("X-JSON", '('.$output.')');
  210. return sfView::HEADER_ONLY;
  211. }
  212. If the action must be rendered by a specific template, ignore the `return` statement and use the `setTemplate()` method instead.
  213. [php]
  214. $this->setTemplate('myCustomTemplate');
  215. ### Skipping to Another Action
  216. In some cases, the action execution ends by requesting a new action execution. For instance, an action handling a form submission in a POST request usually redirects to another action after updating the database. Another example is an action alias: the `index` action is often a way to display a list, and actually forwards to a `list` action.
  217. The action class provides two methods to execute another action:
  218. * If the action forwards the call to another action:
  219. [php]
  220. $this->forward('otherModule', 'index');
  221. * If the action results in a web redirection:
  222. [php]
  223. $this->redirect('otherModule/index');
  224. $this->redirect('http://www.google.com/');
  225. >**NOTE**
  226. >The code located after a forward or a redirect in an action is never executed. You can consider that these calls are equivalent to a `return` statement. They throw an `sfStopException` to stop the execution of the action; this exception is later caught by symfony and simply ignored.
  227. The choice between a redirect or a forward is sometimes tricky. To choose the best solution, keep in mind that a forward is internal to the application and transparent to the user. As far as the user is concerned, the displayed URL is the same as the one requested. In contrast, a redirect is a message to the user's browser, involving a new request from it and a change in the final resulting URL.
  228. If the action is called from a submitted form with `method="post"`, you should always do a redirect. The main advantage is that if the user refreshes the resulting page, the form will not be submitted again; in addition, the back button works as expected by displaying the form and not an alert asking the user if he wants to resubmit a POST request.
  229. There is a special kind of forward that is used very commonly. The `forward404()` method forwards to a "page not found" action. This method is often called when a parameter necessary to the action execution is not present in the request (thus detecting a wrongly typed URL). Listing 6-11 shows an example of a `show` action expecting an `id` parameter.
  230. Listing 6-11 - Use of the `forward404()` Method
  231. [php]
  232. public function executeShow($request)
  233. {
  234. $article = ArticlePeer::retrieveByPK($request->getParameter('id'));
  235. if (!$article)
  236. {
  237. $this->forward404();
  238. }
  239. }
  240. >**TIP**
  241. >If you are looking for the error 404 action and template, you will find them in the `$sf_symfony_ lib_dir/controller/default/` directory. You can customize this page by adding a new `default` module to your application, overriding the one located in the framework, and by defining an `error404` action and an error404Success template inside. Alternatively, you can set the `error_404_module` and `error_404_action` constants in the `settings.yml` file to use an existing action.
  242. Experience shows that, most of the time, an action makes a redirect or a forward after testing something, such as in Listing 6-12. That's why the `sfActions` class has a few more methods, named `forwardIf()`, `forwardUnless()`, `forward404If()`, `forward404Unless()`, `redirectIf()`, and `redirectUnless()`. These methods simply take an additional parameter representing a condition that triggers the execution if tested true (for the `xxxIf()` methods) or false (for the `xxxUnless()` methods), as illustrated in Listing 6-12.
  243. Listing 6-12 - Use of the `forward404If()` Method
  244. [php]
  245. // This action is equivalent to the one shown in Listing 6-11
  246. public function executeShow($request)
  247. {
  248. $article = ArticlePeer::retrieveByPK($request->getParameter('id'));
  249. $this->forward404If(!$article);
  250. }
  251. // So is this one
  252. public function executeShow()
  253. {
  254. $article = ArticlePeer::retrieveByPK($request->getParameter('id'));
  255. $this->forward404Unless($article);
  256. }
  257. Using these methods will not only keep your code short, but it will also make it more readable.
  258. >**TIP**
  259. >When the action calls `forward404()` or its fellow methods, symfony throws an `sfError404Exception` that manages the 404 response. This means that if you need to display a 404 message from somewhere where you don't want to access the controller, you can just throw a similar exception.
  260. ### Repeating Code for Several Actions of a Module
  261. The convention to name actions `executeActionName()` (in the case of an `sfActions` class) or `execute()` (in the case of an `sfAction` class) guarantees that symfony will find the action method. It gives you the ability to add other methods of your own that will not be considered as actions, as long as they don't start with `execute`.
  262. There is another useful convention for when you need to repeat several statements in each action before the actual action execution. You can then extract them into the `preExecute()` method of your action class. You can probably guess how to repeat statements after every action is executed: wrap them in a `postExecute()` method. The syntax of these methods is shown in Listing 6-13.
  263. Listing 6-13 - Using `preExecute()`, `postExecute()`, and Custom Methods in an Action Class
  264. [php]
  265. class mymoduleActions extends sfActions
  266. {
  267. public function preExecute()
  268. {
  269. // The code inserted here is executed at the beginning of each action call
  270. ...
  271. }
  272. public function executeIndex($request)
  273. {
  274. ...
  275. }
  276. public function executeList($request)
  277. {
  278. ...
  279. $this->myCustomMethod(); // Methods of the action class are accessible
  280. }
  281. public function postExecute()
  282. {
  283. // The code inserted here is executed at the end of each action call
  284. ...
  285. }
  286. protected function myCustomMethod()
  287. {
  288. // You can also add your own methods, as long as they don't start with "execute"
  289. // In that case, it's better to declare them as protected or private
  290. ...
  291. }
  292. }
  293. Accessing the Request
  294. ---------------------
  295. The first argument of any action method is the request object, called `sfWebRequest` in symfony. You're already familiar with the `getParameter('myparam')` method, used to retrieve the value of a request parameter by its name. Table 6-1 lists the most useful `sfWebRequest` methods.
  296. Table 6-1 - Methods of the `sfWebRequest` Object
  297. Name | Function | Sample Output
  298. -------------------------------- | -------------------------------------- | -----------------------------------------------------------------------
  299. **Request Information** | |
  300. `isMethod($method)` | Is it a post or a get? | true or false
  301. `getMethod()` | Request method | Returns `sfRequest::GET` or `sfRequest::POST` constants
  302. `getMethodName()` | Request method name | `'POST'`
  303. `getHttpHeader('Server')` | Value of a given HTTP header | `'Apache/2.0.59 (Unix) DAV/2 PHP/5.1.6'`
  304. `getCookie('foo')` | Value of a named cookie | `'bar'`
  305. `isXmlHttpRequest()`* | Is it an Ajax request? | `true`
  306. `isSecure()` | Is it an SSL request? | `true`
  307. **Request Parameters** | |
  308. `hasParameter('foo')` | Is a parameter present in the request? | `true`
  309. `getParameter('foo')` | Value of a named parameter | `'bar'`
  310. `getParameterHolder()->getAll()` | Array of all request parameters |
  311. **URI-Related Information** | |
  312. `getUri()` | Full URI | `'http://localhost/frontend_dev.php/mymodule/myaction'`
  313. `getPathInfo()` | Path info | `'/mymodule/myaction'`
  314. `getReferer()`** | Referrer | `'http://localhost/frontend_dev.php/'`
  315. `getHost()` | Host name | `'localhost'`
  316. `getScriptName()` | Front controller path and name | `'frontend_dev.php'`
  317. **Client Browser Information** | |
  318. `getLanguages()` | Array of accepted languages | `Array( ` ` [0] => fr ` ` [1] => fr_FR ` ` [2] => en_US ` ` [3] => en )`
  319. `getCharsets()` | Array of accepted charsets | `Array( ` ` [0] => ISO-8859-1 ` ` [1] => UTF-8 ` ` [2] => * )`
  320. getAcceptableContentTypes() | Array of accepted content types | `Array( [0] => text/xml [1] => text/html`
  321. \* *Works with prototype, Prototype, Mootools, and jQuery*
  322. ** *Sometimes blocked by proxies*
  323. For multipart requests to which users attach files, the `sfWebRequest` object provides a means to access and move these files, as shown in Listing 6-14. These methods are deprecated in symfony 1.1 (see the form framework and the `sfValidatorFile` class for more information).
  324. Listing 6-14 - The `sfWebRequest` Object Knows How to Handle Attached Files
  325. [php]
  326. class mymoduleActions extends sfActions
  327. {
  328. public function executeUpload($request)
  329. {
  330. if ($request->hasFiles())
  331. {
  332. foreach ($request->getFileNames() as $uploadedFile)
  333. {
  334. $fileName = $request->getFileName($uploadedFile);
  335. $fileSize = $request->getFileSize($uploadedFile);
  336. $fileType = $request->getFileType($uploadedFile);
  337. $fileError = $request->hasFileError($uploadedFile);
  338. $uploadDir = sfConfig::get('sf_upload_dir');
  339. $request->moveFile($uploadedFile, $uploadDir.'/'.$fileName);
  340. }
  341. }
  342. }
  343. }
  344. You don't have to worry about whether your server supports the `$_SERVER` or the `$_ENV` variables, or about default values or server-compatibility issues--the `sfWebRequest` methods do it all for you. Besides, their names are so evident that you will no longer need to browse the PHP documentation to find out how to get information from the request.
  345. >**NOTE**
  346. >The code above uses the `$fileName` as it was when the file was uploaded. As there is a small chance that this gets exploited by sending files with malicious file names, you always should normalize the target filename or generate it.
  347. User Session
  348. ------------
  349. Symfony automatically manages user sessions and is able to keep persistent data between requests for users. It uses the built-in PHP session-handling mechanisms and enhances them to make them more configurable and easier to use.
  350. ### Accessing the User Session
  351. The session object for the current user is accessed in the action with the `getUser()` method and is an instance of the `sfUser` class. This class contains a parameter holder that allows you to store any user attribute in it. This data will be available to other requests until the end of the user session, as shown in Listing 6-15. User attributes can store any type of data (strings, arrays, and associative arrays). They can be set for every individual user, even if that user is not identified.
  352. Listing 6-15 - The `sfUser` Object Can Hold Custom User Attributes Existing Across Requests
  353. [php]
  354. class mymoduleActions extends sfActions
  355. {
  356. public function executeFirstPage($request)
  357. {
  358. $nickname = $request->getParameter('nickname');
  359. // Store data in the user session
  360. $this->getUser()->setAttribute('nickname', $nickname);
  361. }
  362. public function executeSecondPage()
  363. {
  364. // Retrieve data from the user session with a default value
  365. $nickname = $this->getUser()->getAttribute('nickname', 'Anonymous Coward');
  366. }
  367. }
  368. >**CAUTION**
  369. >You can store objects in the user session, but it is strongly discouraged. This is because the session object is serialized between requests. When the session is deserialized, the class of the stored objects must already be loaded, and that's not always the case. In addition, there can be "stalled" objects if you store Propel objects.
  370. Like many getters in symfony, the `getAttribute()` method accepts a second argument, specifying the default value to be used when the attribute is not defined. To check whether an attribute has been defined for a user, use the `hasAttribute()` method. The attributes are stored in a parameter holder that can be accessed by the `getAttributeHolder()` method. It allows for easy cleanup of the user attributes with the usual parameter holder methods, as shown in Listing 6-16.
  371. Listing 6-16 - Removing Data from the User Session
  372. [php]
  373. class mymoduleActions extends sfActions
  374. {
  375. public function executeRemoveNickname()
  376. {
  377. $this->getUser()->getAttributeHolder()->remove('nickname');
  378. }
  379. public function executeCleanup()
  380. {
  381. $this->getUser()->getAttributeHolder()->clear();
  382. }
  383. }
  384. The user session attributes are also available in the templates by default via the `$sf_user` variable, which stores the current `sfUser` object, as shown in Listing 6-17.
  385. Listing 6-17 - Templates Also Have Access to the User Session Attributes
  386. [php]
  387. <p>
  388. Hello, <?php echo $sf_user->getAttribute('nickname') ?>
  389. </p>
  390. >**NOTE**
  391. >If you need to store information just for the duration of the current request--for instance, to pass information through a chain of action calls--you may prefer the `sfRequest` class, which also has `getAttribute()` and `setAttribute()` methods. Only the attributes of the `sfUser` object are persistent between requests.
  392. ### Flash Attributes
  393. A recurrent problem with user attributes is the cleaning of the user session once the attribute is not needed anymore. For instance, you may want to display a confirmation after updating data via a form. As the form-handling action makes a redirect, the only way to pass information from this action to the action it redirects to is to store the information in the user session. But once the confirmation message is displayed, you need to clear the attribute; otherwise, it will remain in the session until it expires.
  394. The flash attribute is an ephemeral attribute that you can define and forget, knowing that it will disappear after the very next request and leave the user session clean for the future. In your action, define the flash attribute like this:
  395. [php]
  396. $this->getUser()->setFlash('notice', $value);
  397. The template will be rendered and delivered to the user, who will then make a new request to another action. In this second action, just get the value of the flash attribute like this:
  398. [php]
  399. $value = $this->getUser()->getFlash('notice');
  400. Then forget about it. After delivering this second page, the `notice` flash attribute will be flushed. And even if you don't require it during this second action, the flash will disappear from the session anyway.
  401. If you need to access a flash attribute from a template, use the `$sf_user` object:
  402. [php]
  403. <?php if ($sf_user->hasFlash('notice')): ?>
  404. <?php echo $sf_user->getFlash('notice') ?>
  405. <?php endif; ?>
  406. or just:
  407. [php]
  408. <?php echo $sf_user->getFlash('notice') ?>
  409. Flash attributes are a clean way of passing information to the very next request.
  410. ### Session Management
  411. Symfony's session-handling feature completely masks the client and server storage of the session IDs to the developer. However, if you want to modify the default behaviors of the session-management mechanisms, it is still possible. This is mostly for advanced users.
  412. On the client side, sessions are handled by cookies. The symfony session cookie is called `symfony`, but you can change its name by editing the `factories.yml` configuration file, as shown in Listing 6-18.
  413. Listing 6-18 - Changing the Session Cookie Name, in `apps/frontend/config/factories.yml`
  414. all:
  415. storage:
  416. class: sfSessionStorage
  417. param:
  418. session_name: my_cookie_name
  419. >**TIP**
  420. >The session is started (with the PHP function `session_start()`) only if the `auto_start` parameter is set to true in factories.yml (which is the case by default). If you want to start the user session manually, disable this setting of the storage factory.
  421. Symfony's session handling is based on PHP sessions. This means that if you want the client-side management of sessions to be handled by URL parameters instead of cookies, you just need to change the `use_trans_sid` setting in your php.ini. Be aware that this is not recommended.
  422. session.use_trans_sid = 1
  423. On the server side, symfony stores user sessions in files by default. You can store them in your database by changing the value of the `class` parameter in `factories.yml`, as shown in Listing 6-19.
  424. Listing 6-19 - Changing the Server Session Storage, in `apps/frontend/config/factories.yml`
  425. all:
  426. storage:
  427. class: sfMySQLSessionStorage
  428. param:
  429. db_table: session # Name of the table storing the sessions
  430. database: propel # Name of the database connection to use
  431. # Optional parameters
  432. db_id_col: sess_id # Name of the column storing the session id
  433. db_data_col: sess_data # Name of the column storing the session data
  434. db_time_col: sess_time # Name of the column storing the session timestamp
  435. The `database` setting defines the database connection to be used. Symfony will then use `databases.yml` (see Chapter 8) to determine the connection settings (host, database name, user, and password) for this connection.
  436. The available session storage classes are `sfMySQLSessionStorage`, `sfMySQLiSessionStorage`, `sfPostgreSQLSessionStorage`, and `sfPDOSessionStorage`; the latter is preferred. To disable session storage completely, you can use the `sfNoStorage` class.
  437. Session expiration occurs automatically after 30 minutes. This default setting can be modified for each environment in the same `factories.yml` configuration file, but this time in the `user` factory, as shown in Listing 6-20.
  438. Listing 6-20 - Changing Session Lifetime, in `apps/frontend/config/factories.yml`
  439. all:
  440. user:
  441. class: myUser
  442. param:
  443. timeout: 1800 # Session lifetime in seconds
  444. To learn more about factories, refer to Chapter 19.
  445. Action Security
  446. ---------------
  447. The ability to execute an action can be restricted to users with certain privileges. The tools provided by symfony for this purpose allow the creation of secure applications, where users need to be authenticated before accessing some features or parts of the application. Securing an application requires two steps: declaring the security requirements for each action and logging in users with privileges so that they can access these secure actions.
  448. ### Access Restriction
  449. Before being executed, every action passes by a special filter that checks if the current user has the privileges to access the requested action. In symfony, privileges are composed of two parts:
  450. * Secure actions require users to be authenticated.
  451. * Credentials are named security privileges that allow organizing security by group.
  452. Restricting access to an action is simply made by creating and editing a YAML configuration file called `security.yml` in the module `config/` directory. In this file, you can specify the security requirements that users must fulfill for each action or for `all` actions. Listing 6-21 shows a sample `security.yml`.
  453. Listing 6-21 - Setting Access Restrictions, in `apps/frontend/modules/mymodule/config/security.yml`
  454. read:
  455. is_secure: off # All users can request the read action
  456. update:
  457. is_secure: on # The update action is only for authenticated users
  458. delete:
  459. is_secure: on # Only for authenticated users
  460. credentials: admin # With the admin credential
  461. all:
  462. is_secure: off # off is the default value anyway
  463. Actions are not secure by default, so when there is no `security.yml` or no mention of an action in it, actions are accessible by everyone. If there is a `security.yml`, symfony looks for the name of the requested action and, if it exists, checks the fulfillment of the security requirements. What happens when a user tries to access a restricted action depends on his credentials:
  464. * If the user is authenticated and has the proper credentials, the action is executed.
  465. * If the user is not identified, he will be redirected to the default login action.
  466. * If the user is identified but doesn't have the proper credentials, he will be redirected to the default secure action, shown in Figure 6-1.
  467. The default login and secure pages are pretty simple, and you will probably want to customize them. You can configure which actions are to be called in case of insufficient privileges in the application `settings.yml` by changing the value of the properties shown in Listing 6-22.
  468. Figure 6-1 - The default secure action page
  469. ![The default secure action page](/images/book/F0601.jpg "The default secure action page")
  470. Listing 6-22 - Default Security Actions Are Defined in `apps/frontend/config/settings.yml`
  471. all:
  472. .actions:
  473. login_module: default
  474. login_action: login
  475. secure_module: default
  476. secure_action: secure
  477. ### Granting Access
  478. To get access to restricted actions, users need to be authenticated and/or to have certain credentials. You can extend a user's privileges by calling methods of the `sfUser` object. The authenticated status of the user is set by the `setAuthenticated()` method and can be checked with `isAuthenticated()`. Listing 6-23 shows a simple example of user authentication.
  479. Listing 6-23 - Setting the Authenticated Status of a User
  480. [php]
  481. class myAccountActions extends sfActions
  482. {
  483. public function executeLogin($request)
  484. {
  485. if ($request->getParameter('login') == 'foobar')
  486. {
  487. $this->getUser()->setAuthenticated(true);
  488. }
  489. }
  490. public function executeLogout()
  491. {
  492. $this->getUser()->setAuthenticated(false);
  493. }
  494. }
  495. Credentials are a bit more complex to deal with, since you can check, add, remove, and clear credentials. Listing 6-24 describes the credential methods of the `sfUser` class.
  496. Listing 6-24 - Dealing with User Credentials in an Action
  497. [php]
  498. class myAccountActions extends sfActions
  499. {
  500. public function executeDoThingsWithCredentials()
  501. {
  502. $user = $this->getUser();
  503. // Add one or more credentials
  504. $user->addCredential('foo');
  505. $user->addCredentials('foo', 'bar');
  506. // Check if the user has a credential
  507. echo $user->hasCredential('foo'); => true
  508. // Check if the user has both credentials
  509. echo $user->hasCredential(array('foo', 'bar')); => true
  510. // Check if the user has one of the credentials
  511. echo $user->hasCredential(array('foo', 'bar'), false); => true
  512. // Remove a credential
  513. $user->removeCredential('foo');
  514. echo $user->hasCredential('foo'); => false
  515. // Remove all credentials (useful in the logout process)
  516. $user->clearCredentials();
  517. echo $user->hasCredential('bar'); => false
  518. }
  519. }
  520. If a user has the `foo` credential, that user will be able to access the actions for which the `security.yml` requires that credential. Credentials can also be used to display only authorized content in a template, as shown in Listing 6-25.
  521. Listing 6-25 - Dealing with User Credentials in a Template
  522. [php]
  523. <ul>
  524. <li><?php echo link_to('section1', 'content/section1') ?></li>
  525. <li><?php echo link_to('section2', 'content/section2') ?></li>
  526. <?php if ($sf_user->hasCredential('section3')): ?>
  527. <li><?php echo link_to('section3', 'content/section3') ?></li>
  528. <?php endif; ?>
  529. </ul>
  530. As for the authenticated status, credentials are often given to users during the login process. This is why the `sfUser` object is often extended to add login and logout methods, in order to set the security status of users in a central place.
  531. >**TIP**
  532. >Among the symfony plug-ins, the `sfGuardPlugin` (http://trac.symfony-project.org/wiki/sfGuardPlugin) extends the session class to make login and logout easy. Refer to Chapter 17 for more information.
  533. ### Complex Credentials
  534. The YAML syntax used in the security.yml file allows you to restrict access to users having a combination of credentials, using either AND-type or OR-type associations. With such a combination, you can build a complex workflow and user privilege management system--for instance, a content management system (CMS) back-office accessible only to users with the admin credential, where articles can be edited only by users with the `editor` credential and published only by the ones with the `publisher` credential. Listing 6-26 shows this example.
  535. Listing 6-26 - Credentials Combination Syntax
  536. editArticle:
  537. credentials: [ admin, editor ] # admin AND editor
  538. publishArticle:
  539. credentials: [ admin, publisher ] # admin AND publisher
  540. userManagement:
  541. credentials: [[ admin, superuser ]] # admin OR superuser
  542. Each time you add a new level of square brackets, the logic swaps between AND and OR. So you can create very complex credential combinations, such as this:
  543. credentials: [[root, [supplier, [owner, quasiowner]], accounts]]
  544. # root OR (supplier AND (owner OR quasiowner)) OR accounts
  545. Validation and Error-Handling Methods
  546. -------------------------------------
  547. >**NOTE**
  548. >The features described in this section are deprecated in symfony 1.1 and only work if you enable the `sfCompat10` plugin.
  549. Validating the action input--mostly request parameters--is a repetitive and tedious task. Symfony offers a built-in request validation system, using methods of the action class.
  550. Let's start with an example. When a user makes a request for `myAction`, symfony always looks for a method called `validateMyAction()` first. If it is found, then symfony executes it. The return value of this validation method determines the next method to be executed: if it returns `true`, then `executeMyAction()` is executed; otherwise, `handleErrorMyAction()` is executed. And, if in the latter case, handleErrorMyAction() doesn't exist, symfony looks for a generic handleError() method. If that doesn't exist either, it simply returns `sfView::ERROR` to render the `myActionError. php` template. Figure 6-2 depicts this process.
  551. Figure 6-2 - The validation process
  552. ![The validation process](/images/book/F0602.png "The validation process")
  553. So the key to validation is to respect the naming conventions for the action methods:
  554. * `validateActionName` is the validation method, returning `true` or `false`. It is the first method looked for when the action `ActionName` is requested. If it doesn't exist, the action method is executed directly.
  555. * `handleErrorActionName` is the method called when the validation method fails. If it doesn't exist, the `Error` template is displayed.
  556. * `executeActionName` is the action method. It must exist for all actions.
  557. Listing 6-27 shows an example of an action class with validation methods. Whether the validation passes or fails in this example, the `myActionSuccess.php` template will be executed, but not with the same parameters.
  558. Listing 6-27 - Sample Validation Methods
  559. [php]
  560. class mymoduleActions extends sfActions
  561. {
  562. public function validateMyAction()
  563. {
  564. return $this->getRequestParameter('id') > 0;
  565. }
  566. public function handleErrorMyAction()
  567. {
  568. $this->message = "Invalid parameters";
  569. return sfView::SUCCESS;
  570. }
  571. public function executeMyAction()
  572. {
  573. $this->message = "The parameters are correct";
  574. }
  575. }
  576. You can put any code you want in the `validate()` methods. Just make sure they return either `true` or `false`. As it is a method of the `sfActions` class, it has access to the `sfRequest` and `sfUser` objects as well, which can be really useful for input and context validation.
  577. You could use this mechanism to implement form validation (that is, control the values entered by the user in a form before processing it), but this is the type of repetitive task for which symfony provides automated tools, as described in Chapter 10.
  578. Filters
  579. -------
  580. The security process can be understood as a filter by which all requests must pass before executing the action. According to some tests executed in the filter, the processing of the request is modified--for instance, by changing the action executed (default/secure instead of the requested action in the case of the security filter). Symfony extends this idea to filter classes. You can specify any number of filter classes to be executed before the action execution or before the response rendering, and do this for every request. You can see filters as a way to package some code, similar to `preExecute()` and `postExecute()`, but at a higher level (for a whole application instead of for a whole module).
  581. ### The Filter Chain
  582. Symfony actually sees the processing of a request as a chain of filters. When a request is received by the framework, the first filter (which is always the `sfRenderingFilter`) is executed. At some point, it calls the next filter in the chain, then the next, and so on. When the last filter (which is always `sfExecutionFilter`) is executed, the previous filter can finish, and so on back to the rendering filter. Figure 6-3 illustrates this idea with a sequence diagram, using an artificially small filter chain (the real one contains more filters).
  583. Figure 6-3 - Sample filter chain
  584. ![Sample filter chain](/images/book/F0603.png "Sample filter chain")
  585. This process justifies the structure of the filter classes. They all extend the `sfFilter` class, and contain one `execute()` method, expecting a `$filterChain` object as parameter. Somewhere in this method, the filter passes to the next filter in the chain by calling `$filterChain->execute()`. See Listing 6-28 for an example. So basically, filters are divided into two parts:
  586. * The code before the call to `$filterChain->execute()` executes before the action execution.
  587. * The code after the call to `$filterChain->execute()` executes after the action execution and before the rendering.
  588. Listing 6-28 - Filter Class Struture
  589. [php]
  590. class myFilter extends sfFilter
  591. {
  592. public function execute ($filterChain)
  593. {
  594. // Code to execute before the action execution
  595. ...
  596. // Execute next filter in the chain
  597. $filterChain->execute();
  598. // Code to execute after the action execution, before the rendering
  599. ...
  600. }
  601. }
  602. The default filter chain is defined in an application configuration file called `filters.yml`, and is shown in Listing 6-29. This file lists the filters that are to be executed for every request.
  603. Listing 6-29 - Default Filter Chain, in `frontend/config/filters.yml`
  604. rendering: ~
  605. security: ~
  606. # Generally, you will want to insert your own filters here
  607. cache: ~
  608. common: ~
  609. execution: ~
  610. These declarations have no parameter (the tilde character, `~`, means "null" in YAML), because they inherit the parameters defined in the symfony core. In the core, symfony defines `class` and `param` settings for each of these filters. For instance, Listing 6-30 shows the default parameters for the `rendering` filter.
  611. Listing 6-30 - Default Parameters of the rendering Filter, in `$sf_symfony_lib_dir/config/config/filters.yml`
  612. rendering:
  613. class: sfRenderingFilter # Filter class
  614. param: # Filter parameters
  615. type: rendering
  616. By leaving the empty value (`~`) in the application `filters.yml`, you tell symfony to apply the filter with the default settings defined in the core.
  617. You can customize the filter chain in various ways:
  618. * Disable some filters from the chain by adding an `enabled: off` parameter. For instance, to disable the `common` filter, which inserts CSS and JavaScript into the head, write:
  619. common:
  620. enabled: off
  621. * Do not remove an entry from the `filters.yml` to disable a filter; symfony would throw an exception in this case.
  622. * Add your own declarations somewhere in the chain (usually after the `security` filter) to add a custom filter (as discussed in the next section). Be aware that the `rendering` filter must be the first entry, and the `execution` filter must be the last entry of the filter chain.
  623. * Override the default class and parameters of the default filters (notably to modify the security system and use your own security filter).
  624. ### Building Your Own Filter
  625. It is pretty simple to build a filter. Create a class definition similar to the one shown in Listing 6-28, and place it in one of the project's lib/ folders to take advantage of the autoloading feature.
  626. As an action can forward or redirect to another action and consequently relaunch the full chain of filters, you might want to restrict the execution of your own filters to the first action call of the request. The `isFirstCall()` method of the `sfFilter` class returns a Boolean for this purpose. This call only makes sense before the action execution.
  627. These concepts are clearer with an example. Listing 6-31 shows a filter used to auto-log users with a specific `MyWebSite` cookie, which is supposedly created by the login action. It is a rudimentary but working way to implement the "remember me" feature offered in login forms.
  628. Listing 6-31 - Sample Filter Class File, Saved in `apps/frontend/lib/rememberFilter.class.php`
  629. [php]
  630. class rememberFilter extends sfFilter
  631. {
  632. public function execute($filterChain)
  633. {
  634. // Execute this filter only once
  635. if ($this->isFirstCall())
  636. {
  637. // Filters don't have direct access to the request and user objects.
  638. // You will need to use the context object to get them
  639. $request = $this->getContext()->getRequest();
  640. $user = $this->getContext()->getUser();
  641. if ($request->getCookie('MyWebSite'))
  642. {
  643. // sign in
  644. $user->setAuthenticated(true);
  645. }
  646. }
  647. // Execute next filter
  648. $filterChain->execute();
  649. }
  650. }
  651. In some cases, instead of continuing the filter chain execution, you will need to forward to a specific action at the end of a filter. `sfFilter` doesn't have a `forward()` method, but `sfController` does, so you can simply do that by calling the following:
  652. [php]
  653. return $this->getContext()->getController()->forward('mymodule', 'myAction');
  654. >**NOTE**
  655. >The `sfFilter` class has an `initialize()` method, executed when the filter object is created. You can override it in your custom filter if you need to deal with filter parameters (defined in `filters.yml`, as described next) in your own way.
  656. ### Filter Activation and Parameters
  657. Creating a filter file is not enough to activate it. You need to add your filter to the filter chain, and for that, you must declare the filter class in the `filters.yml`, located in the application or in the module `config/` directory, as shown in Listing 6-32.
  658. Listing 6-32 - Sample Filter Activation File, Saved in `apps/frontend/config/filters.yml`
  659. rendering: ~
  660. security: ~
  661. remember: # Filters need a unique name
  662. class: rememberFilter
  663. param:
  664. cookie_name: MyWebSite
  665. condition: %APP_ENABLE_REMEMBER_ME%
  666. cache: ~
  667. common: ~
  668. execution: ~
  669. When activated, the filter is executed for each request. The filter configuration file can contain one or more parameter definitions under the `param` key. The filter class has the ability to get the value of these parameters with the getParameter() method. Listing 6-33 demonstrates how to get a filter parameter value.
  670. Listing 6-33 - Getting the Parameter Value, in `apps/frontend/lib/rememberFilter.class.php`
  671. [php]
  672. class rememberFilter extends sfFilter
  673. {
  674. public function execute ($filterChain)
  675. {
  676. // ...
  677. if ($request->getCookie($this->getParameter('cookie_name')))
  678. {
  679. // ...
  680. }
  681. // ...
  682. }
  683. }
  684. The `condition` parameter is tested by the filter chain to see if the filter must be executed. So your filter declarations can rely on an application configuration, just like the one in Listing 6-32. The remember filter will be executed only if your application `app.yml` shows this:
  685. all:
  686. enable_remember_me: on
  687. ### Sample Filters
  688. The filter feature is useful to repeat code for every action. For instance, if you use a distant analytics system, you probably need to put a code snippet calling a distant tracker script in every page. You could put this code in the global layout, but then it would be active for all of the application. Alternatively, you could place it in a filter, such as the one shown in Listing 6-34, and activate it on a per-module basis.
  689. Listing 6-34 - Google Analytics Filter
  690. [php]
  691. class sfGoogleAnalyticsFilter extends sfFilter
  692. {
  693. public function execute($filterChain)
  694. {
  695. // Nothing to do before the action
  696. $filterChain->execute();
  697. // Decorate the response with the tracker code
  698. $googleCode = '
  699. <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
  700. </script>
  701. <script type="text/javascript">
  702. _uacct="UA-'.$this->getParameter('google_id').'";urchinTracker();
  703. </script>';
  704. $response = $this->getContext()->getResponse();
  705. $response->setContent(str_ireplace('</body>', $googleCode.'</body>',$response->getContent()));
  706. }
  707. }
  708. Be aware that this filter is not perfect, as it should not add the tracker on responses that are not HTML.
  709. Another example would be a filter that switches the request to SSL if it is not already, to secure the communication, as shown in Listing 6-35.
  710. Listing 6-35 - Secure Communication Filter
  711. [php]
  712. class sfSecureFilter extends sfFilter
  713. {
  714. public function execute($filterChain)
  715. {
  716. $context = $this->getContext();
  717. $request = $context->getRequest();
  718. if (!$request->isSecure())
  719. {
  720. $secure_url = str_replace('http', 'https', $request->getUri());
  721. return $context->getController()->redirect($secure_url);
  722. // We don't continue the filter chain
  723. }
  724. else
  725. {
  726. // The request is already secure, so we can continue
  727. $filterChain->execute();
  728. }
  729. }
  730. }
  731. Filters are used extensively in plug-ins, as they allow you to extend the features of an application globally. Refer to Chapter 17 to learn more about plug-ins, and see the online wiki ([http://trac.symfony-project.org/](http://trac.symfony-project.org/)) for more filter examples.
  732. Module Configuration
  733. --------------------
  734. A few module behaviors rely on configuration. To modify them, you must create a `module.yml` file in the module's `config/` directory and define settings on a per-environment basis (or under the `all:` header for all environments). Listing 6-36 shows an example of a `module.yml` file for the `mymodule` module.
  735. Listing 6-36 - Module Configuration, in `apps/frontend/modules/mymodule/config/module.yml`
  736. all: # For all environments
  737. enabled: true
  738. is_internal: false
  739. view_class: sfPHP
  740. The enabled parameter allows you to disable all actions of a module. All actions are redirected to the `module_disabled_module`/`module_disabled_action` action (as defined in `settings.yml`).
  741. The `is_internal` parameter allows you to restrict the execution of all actions of a module to internal calls. For example, this is useful for mail actions that you must be able to call from another action, to send an e-mail message, but not from the outside.
  742. The `view_class` parameter defines the view class. It must inherit from `sfView`. Overriding this value allows you to use other view systems, with other templating engines, such as Smarty.
  743. Summary
  744. -------
  745. In symfony, the controller layer is split into two parts: the front controller, which is the unique entry point to the application for a given environment, and the actions, which contain the page logic. An action has the ability to determine how its view will be executed, by returning one of the `sfView` constants. Inside an action, you can manipulate the different elements of the context, including the request object (`sfRequest`) and the current user session object (`sfUser`).
  746. Combining the power of the session object, the action object, and the security configuration, symfony provides a complete security system, with access restriction and credentials. Special `validate()` and `handleError()` methods in actions allow handling of request validation. And if the `preExecute()` and `postExecute()` methods are made for reusability of code inside a module, the filters authorize the same reusability for all the applications by making controller code executed for every request.