02-Exploring-Symfony-s-Code.txt 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. Chapter 2 - Exploring Symfony's Code
  2. ====================================
  3. At first glance, the code behind a symfony-driven application can seem quite daunting. It consists of many directories and scripts, and the files are a mix of PHP classes, HTML, and even an intermingling of the two. You'll also see references to classes that are otherwise nowhere to be found within the application folder, and the directory depth stretches to six levels. But once you understand the reason behind all of this seeming complexity, you'll suddenly feel like it's so natural that you wouldn't trade the symfony application structure for any other. This chapter explains away that intimidated feeling.
  4. The MVC Pattern
  5. ---------------
  6. Symfony is based on the classic web design pattern known as the MVC architecture, which consists of three levels:
  7. * The Model represents the information on which the application operates--its business logic.
  8. * The View renders the model into a web page suitable for interaction with the user.
  9. * The Controller responds to user actions and invokes changes on the model or view as appropriate.
  10. Figure 2-1 illustrates the MVC pattern.
  11. The MVC architecture separates the business logic (model) and the presentation (view), resulting in greater maintainability. For instance, if your application should run on both standard web browsers and handheld devices, you just need a new view; you can keep the original controller and model. The controller helps to hide the detail of the protocol used for the request (HTTP, console mode, mail, and so on) from the model and the view. And the model abstracts the logic of the data, which makes the view and the action independent of, for instance, the type of database used by the application.
  12. Figure 2-1 - The MVC pattern
  13. ![The MVC pattern](/images/book/F0201.png "The MVC pattern")
  14. ### MVC Layering
  15. To help you understand MVC's advantages, let's see how to convert a basic PHP application to an MVC-architectured application. A list of posts for a weblog application will be a perfect example.
  16. #### Flat Programming
  17. In a flat PHP file, displaying a list of database entries might look like the script presented in Listing 2-1.
  18. Listing 2-1 - A Flat Script
  19. [php]
  20. <?php
  21. // Connecting, selecting database
  22. $link = mysql_connect('localhost', 'myuser', 'mypassword');
  23. mysql_select_db('blog_db', $link);
  24. // Performing SQL query
  25. $result = mysql_query('SELECT date, title FROM post', $link);
  26. ?>
  27. <html>
  28. <head>
  29. <title>List of Posts</title>
  30. </head>
  31. <body>
  32. <h1>List of Posts</h1>
  33. <table>
  34. <tr><th>Date</th><th>Title</th></tr>
  35. <?php
  36. // Printing results in HTML
  37. while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  38. {
  39. echo "\t<tr>\n";
  40. printf("\t\t<td> %s </td>\n", $row['date']);
  41. printf("\t\t<td> %s </td>\n", $row['title']);
  42. echo "\t</tr>\n";
  43. }
  44. ?>
  45. </table>
  46. </body>
  47. </html>
  48. <?php
  49. // Closing connection
  50. mysql_close($link);
  51. ?>
  52. That's quick to write, fast to execute, and impossible to maintain. The following are the major problems with this code:
  53. * There is no error-checking (what if the connection to the database fails?).
  54. * HTML and PHP code are mixed, even interwoven together.
  55. * The code is tied to a MySQL database.
  56. #### Isolating the Presentation
  57. The `echo` and `printf` calls in Listing 2-1 make the code difficult to read. Modifying the HTML code to enhance the presentation is a hassle with the current syntax. So the code can be split into two parts. First, the pure PHP code with all the business logic goes in a controller script, as shown in Listing 2-2.
  58. Listing 2-2 - The Controller Part, in `index.php`
  59. [php]
  60. <?php
  61. // Connecting, selecting database
  62. $link = mysql_connect('localhost', 'myuser', 'mypassword');
  63. mysql_select_db('blog_db', $link);
  64. // Performing SQL query
  65. $result = mysql_query('SELECT date, title FROM post', $link);
  66. // Filling up the array for the view
  67. $posts = array();
  68. while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  69. {
  70. $posts[] = $row;
  71. }
  72. // Closing connection
  73. mysql_close($link);
  74. // Requiring the view
  75. require('view.php');
  76. The HTML code, containing template-like PHP syntax, is stored in a view script, as shown in Listing 2-3.
  77. Listing 2-3 - The View Part, in `view.php`
  78. [php]
  79. <html>
  80. <head>
  81. <title>List of Posts</title>
  82. </head>
  83. <body>
  84. <h1>List of Posts</h1>
  85. <table>
  86. <tr><th>Date</th><th>Title</th></tr>
  87. <?php foreach ($posts as $post): ?>
  88. <tr>
  89. <td><?php echo $post['date'] ?></td>
  90. <td><?php echo $post['title'] ?></td>
  91. </tr>
  92. <?php endforeach; ?>
  93. </table>
  94. </body>
  95. </html>
  96. A good rule of thumb to determine whether the view is clean enough is that it should contain only a minimum amount of PHP code, in order to be understood by an HTML designer without PHP knowledge. The most common statements in views are `echo`, `if/endif`, `foreach/endforeach`, and that's about all. Also, there should not be PHP code echoing HTML tags.
  97. All the logic is moved to the controller script, and contains only pure PHP code, with no HTML inside. As a matter of fact, you should imagine that the same controller could be reused for a totally different presentation, perhaps in a PDF file or an XML structure.
  98. #### Isolating the Data Manipulation
  99. Most of the controller script code is dedicated to data manipulation. But what if you need the list of posts for another controller, say one that would output an RSS feed of the weblog posts? What if you want to keep all the database queries in one place, to avoid code duplication? What if you decide to change the data model so that the `post` table gets renamed `weblog_post`? What if you want to switch to PostgreSQL instead of MySQL? In order to make all that possible, you need to remove the data-manipulation code from the controller and put it in another script, called the model, as shown in Listing 2-4.
  100. Listing 2-4 - The Model Part, in `model.php`
  101. [php]
  102. <?php
  103. function getAllPosts()
  104. {
  105. // Connecting, selecting database
  106. $link = mysql_connect('localhost', 'myuser', 'mypassword');
  107. mysql_select_db('blog_db', $link);
  108. // Performing SQL query
  109. $result = mysql_query('SELECT date, title FROM post', $link);
  110. // Filling up the array
  111. $posts = array();
  112. while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  113. {
  114. $posts[] = $row;
  115. }
  116. // Closing connection
  117. mysql_close($link);
  118. return $posts;
  119. }
  120. The revised controller is presented in Listing 2-5.
  121. Listing 2-5 - The Controller Part, Revised, in `index.php`
  122. [php]
  123. <?php
  124. // Requiring the model
  125. require_once('model.php');
  126. // Retrieving the list of posts
  127. $posts = getAllPosts();
  128. // Requiring the view
  129. require('view.php');
  130. The controller becomes easier to read. Its sole task is to get the data from the model and pass it to the view. In more complex applications, the controller also deals with the request, the user session, the authentication, and so on. The use of explicit names for the functions of the model even makes code comments unnecessary in the controller.
  131. The model script is dedicated to data access and can be organized accordingly. All parameters that don't depend on the data layer (like request parameters) must be given by the controller and not accessed directly by the model. The model functions can be easily reused in another controller.
  132. ### Layer Separation Beyond MVC
  133. So the principle of the MVC architecture is to separate the code into three layers, according to its nature. Data logic code is placed within the model, presentation code within the view, and application logic within the controller.
  134. Other additional design patterns can make the coding experience even easier. The model, view, and controller layers can be further subdivided.
  135. #### Database Abstraction
  136. The model layer can be split into a data access layer and a database abstraction layer. That way, data access functions will not use database-dependent query statements, but call some other functions that will do the queries themselves. If you change your database system later, only the database abstraction layer will need updating.
  137. A sample database abstraction layer is presented in Listing 2-6, followed by an example of a MySQL-specific data access layer in Listing 2-7.
  138. Listing 2-6 - The Database Abstraction Part of the Model
  139. [php]
  140. <?php
  141. function open_connection($host, $user, $password)
  142. {
  143. return mysql_connect($host, $user, $password);
  144. }
  145. function close_connection($link)
  146. {
  147. mysql_close($link);
  148. }
  149. function query_database($query, $database, $link)
  150. {
  151. mysql_select_db($database, $link);
  152. return mysql_query($query, $link);
  153. }
  154. function fetch_results($result)
  155. {
  156. return mysql_fetch_array($result, MYSQL_ASSOC);
  157. }
  158. Listing 2-7 - The Data Access Part of the Model
  159. [php]
  160. function getAllPosts()
  161. {
  162. // Connecting to database
  163. $link = open_connection('localhost', 'myuser', 'mypassword');
  164. // Performing SQL query
  165. $result = query_database('SELECT date, title FROM post', 'blog_db', $link);
  166. // Filling up the array
  167. $posts = array();
  168. while ($row = fetch_results($result))
  169. {
  170. $posts[] = $row;
  171. }
  172. // Closing connection
  173. close_connection($link);
  174. return $posts;
  175. }
  176. You can check that no database-engine dependent functions can be found in the data access layer, making it database-independent. Additionally, the functions created in the database abstraction layer can be reused for many other model functions that need access to the database.
  177. >**NOTE**
  178. >The examples in Listings 2-6 and 2-7 are still not very satisfactory, and there is some work left to do to have a full database abstraction (abstracting the SQL code through a database-independent query builder, moving all functions into a class, and so on). But the purpose of this book is not to show you how to write all that code by hand, and you will see in Chapter 8 that symfony natively does all the abstraction very well.
  179. #### View Elements
  180. The view layer can also benefit from some code separation. A web page often contains consistent elements throughout an application: the page headers, the graphical layout, the footer, and the global navigation. Only the inner part of the page changes. That's why the view is separated into a layout and a template. The layout is usually global to the application, or to a group of pages. The template only puts in shape the variables made available by the controller. Some logic is needed to make these components work together, and this view logic layer will keep the name view. According to these principles, the view part of Listing 2-3 can be separated into three parts, as shown in Listings 2-8, 2-9, and 2-10.
  181. Listing 2-8 - The Template Part of the View, in `mytemplate.php`
  182. [php]
  183. <h1>List of Posts</h1>
  184. <table>
  185. <tr><th>Date</th><th>Title</th></tr>
  186. <?php foreach ($posts as $post): ?>
  187. <tr>
  188. <td><?php echo $post['date'] ?></td>
  189. <td><?php echo $post['title'] ?></td>
  190. </tr>
  191. <?php endforeach; ?>
  192. </table>
  193. Listing 2-9 - The View Logic Part of the View
  194. [php]
  195. <?php
  196. $title = 'List of Posts';
  197. $content = include('mytemplate.php');
  198. Listing 2-10 - The Layout Part of the View
  199. [php]
  200. <html>
  201. <head>
  202. <title><?php echo $title ?></title>
  203. </head>
  204. <body>
  205. <?php echo $content ?>
  206. </body>
  207. </html>
  208. #### Action and Front Controller
  209. The controller doesn't do much in the previous example, but in real web applications, the controller has a lot of work. An important part of this work is common to all the controllers of the application. The common tasks include request handling, security handling, loading the application configuration, and similar chores. This is why the controller is often divided into a front controller, which is unique for the whole application, and actions, which contain only the controller code specific to one page.
  210. One of the great advantages of a front controller is that it offers a unique entry point to the whole application. If you ever decide to close the access to the application, you will just need to edit the front controller script. In an application without a front controller, each individual controller would need to be turned off.
  211. #### Object Orientation
  212. All the previous examples use procedural programming. The OOP capabilities of modern languages make the programming even easier, since objects can encapsulate logic, inherit from one another, and provide clean naming conventions.
  213. Implementing an MVC architecture in a language that is not object-oriented raises namespace and code-duplication issues, and the overall code is difficult to read.
  214. Object orientation allows developers to deal with such things as the view object, the controller object, and the model classes, and to transform all the functions in the previous examples into methods. It is a must for MVC architectures.
  215. >**TIP**
  216. >If you want to learn more about design patterns for web applications in an object-oriented context, read Patterns of Enterprise Application Architecture by Martin Fowler (Addison-Wesley, ISBN: 0-32112-742-0). Code examples in Fowler's book are in Java or C#, but are still quite readable for a PHP developer.
  217. ### Symfony's MVC Implementation
  218. Hold on a minute. For a single page listing the posts in a weblog, how many components are required? As illustrated in Figure 2-2, we have the following parts:
  219. * Model layer
  220. * Database abstraction
  221. * Data access
  222. * View layer
  223. * View
  224. * Template
  225. * Layout
  226. * Controller layer
  227. * Front controller
  228. * Action
  229. Seven scripts--a whole lot of files to open and to modify each time you create a new page! However, symfony makes things easy. While taking the best of the MVC architecture, symfony implements it in a way that makes application development fast and painless.
  230. First of all, the front controller and the layout are common to all actions in an application. You can have multiple controllers and layouts, but you need only one of each. The front controller is pure MVC logic component, and you will never need to write a single one, because symfony will generate it for you.
  231. The other good news is that the classes of the model layer are also generated automatically, based on your data structure. This is the job of the Propel library, which provides class skeletons and code generation. If Propel finds foreign key constraints or date fields, it will provide special accessor and mutator methods that will make data manipulation a piece of cake. And the database abstraction is totally invisible to you, because it is dealt with by another component, called Creole. So if you decide to change your database engine at one moment, you have zero code to rewrite. You just need to change one configuration parameter.
  232. And the last thing is that the view logic can be easily translated as a simple configuration file, with no programming needed.
  233. Figure 2-2 - Symfony workflow
  234. ![Symfony workflow](/images/book/F0202.png "Symfony workflow")
  235. That means that the list of posts described in our example would require only three files to work in symfony, as shown in Listings 2-11, 2-12, and 2-13.
  236. Listing 2-11 - `list` Action, in `myproject/apps/myapp/modules/weblog/actions/actions.class.php`
  237. [php]
  238. <?php
  239. class weblogActions extends sfActions
  240. {
  241. public function executeList()
  242. {
  243. $this->posts = PostPeer::doSelect(new Criteria());
  244. }
  245. }
  246. Listing 2-12 - `list` Template, in `myproject/apps/myapp/modules/weblog/templates/listSuccess.php`
  247. [php]
  248. <?php slot('title', 'List of Posts') ?>
  249. <h1>List of Posts</h1>
  250. <table>
  251. <tr><th>Date</th><th>Title</th></tr>
  252. <?php foreach ($posts as $post): ?>
  253. <tr>
  254. <td><?php echo $post->getDate() ?></td>
  255. <td><?php echo $post->getTitle() ?></td>
  256. </tr>
  257. <?php endforeach; ?>
  258. </table>
  259. In addition, you will still need to define a layout, as shown in Listing 2-13, but it will be reused many times.
  260. Listing 2-13 - Layout, in `myproject/apps/myapp/templates/layout.php`
  261. [php]
  262. <html>
  263. <head>
  264. <title><?php include_slot('title') ?></title>
  265. </head>
  266. <body>
  267. <?php echo $sf_content ?>
  268. </body>
  269. </html>
  270. And that is really all you need. This is the exact code required to display the very same page as the flat script shown earlier in Listing 2-1. The rest (making all the components work together) is handled by symfony. If you count the lines, you will see that creating the list of posts in an MVC architecture with symfony doesn't require more time or coding than writing a flat file. Nevertheless, it gives you huge advantages, notably clear code organization, reusability, flexibility, and much more fun. And as a bonus, you have XHTML conformance, debug capabilities, easy configuration, database abstraction, smart URL routing, multiple environments, and many more development tools.
  271. ### Symfony Core Classes
  272. The MVC implementation in symfony uses several classes that you will meet quite often in this book:
  273. * `sfController` is the controller class. It decodes the request and hands it to the action.
  274. * `sfRequest` stores all the request elements (parameters, cookies, headers, and so on).
  275. * `sfResponse` contains the response headers and contents. This is the object that will eventually be converted to an HTML response and be sent to the user.
  276. * The context (retrieved by `sfContext::getInstance()`) stores a reference to all the core objects and the current configuration; it is accessible from everywhere.
  277. You will learn more about these objects in Chapter 6.
  278. As you can see, all the symfony classes use the `sf` prefix, as do the symfony core variables in the templates. This should avoid name collisions with your own classes and variables, and make the core framework classes sociable and easy to recognize.
  279. >**NOTE**
  280. >Among the coding standards used in symfony, UpperCamelCase is the standard for class and variable naming. Two exceptions exist: core symfony classes start with `sf`, which is lowercase, and variables found in templates use the underscore-separated syntax.
  281. Code Organization
  282. -----------------
  283. Now that you know the different components of a symfony application, you're probably wondering how they are organized. Symfony organizes code in a project structure and puts the project files into a standard tree structure.
  284. ### Project Structure: Applications, Modules, and Actions
  285. In symfony, a project is a set of services and operations available under a given domain name, sharing the same object model.
  286. Inside a project, the operations are grouped logically into applications. An application can normally run independently of the other applications of the same project. In most cases, a project will contain two applications: one for the front-office and one for the back-office, sharing the same database. But you can also have one project containing many mini-sites, with each site as a different application. Note that hyperlinks between applications must be in the absolute form.
  287. Each application is a set of one or more modules. A module usually represents a page or a group of pages with a similar purpose. For example, you might have the modules `home`, `articles`, `help`, `shoppingCart`, `account`, and so on.
  288. Modules hold actions, which represent the various actions that can be done in a module. For example, a `shoppingCart` module can have `add`, `show`, and `update` actions. Generally, actions can be described by a verb. Dealing with actions is almost like dealing with pages in a classic web application, although two actions can result in the same page (for instance, adding a comment to a post in a weblog will redisplay the post with the new comment).
  289. >**TIP**
  290. >If this represents too many levels for a beginning project, it is very easy to group all actions into one single module, so that the file structure can be kept simple. When the application gets more complex, it will be time to organize actions into separate modules. As mentioned in Chapter 1, rewriting code to improve its structure or readability (but preserving its behavior) is called refactoring, and you will do this a lot when applying RAD principles.
  291. Figure 2-3 shows a sample code organization for a weblog project, in a project/application/module/action structure. But be aware that the actual file tree structure of the project will differ from the setup shown in the figure.
  292. Figure 2-3 - Example of code organization
  293. ![Example of code organization](/images/book/F0203.png "Example of code organization")
  294. ### File Tree Structure
  295. All web projects generally share the same types of contents, such as the following:
  296. * A database, such as MySQL or PostgreSQL
  297. * Static files (HTML, images, JavaScript files, style sheets, and so on)
  298. * Files uploaded by the site users and administrators
  299. * PHP classes and libraries
  300. * Foreign libraries (third-party scripts)
  301. * Batch files (scripts to be launched by a command line or via a cron table)
  302. * Log files (traces written by the application and/or the server)
  303. * Configuration files
  304. Symfony provides a standard file tree structure to organize all these contents in a logical way, consistent with the architecture choices (MVC pattern and project/application/module grouping). This is the tree structure that is automatically created when initializing every project, application, or module. Of course, you can customize it completely, to reorganize the files and directories at your convenience or to match your client's requirements.
  305. #### Root Tree Structure
  306. These are the directories found at the root of a symfony project:
  307. apps/
  308. frontend/
  309. backend/
  310. cache/
  311. config/
  312. data/
  313. sql/
  314. doc/
  315. lib/
  316. model/
  317. log/
  318. plugins/
  319. test/
  320. bootstrap/
  321. unit/
  322. functional/
  323. web/
  324. css/
  325. images/
  326. js/
  327. uploads/
  328. Table 2-1 describes the contents of these directories.
  329. Table 2-1 - Root Directories
  330. Directory | Description
  331. ---------- | ------------
  332. `apps/` | Contains one directory for each application of the project (typically, `frontend` and `backend` for the front and back office).
  333. `cache/` | Contains the cached version of the configuration, and (if you activate it) the cache version of the actions and templates of the project. The cache mechanism (detailed in Chapter 12) uses these files to speed up the answer to web requests. Each application will have a subdirectory here, containing preprocessed PHP and HTML files.
  334. `config/` | Holds the general configuration of the project.
  335. `data/` | Here, you can store the data files of the project, like a database schema, a SQL file that creates tables, or even a SQLite database file.
  336. `doc/` | Stores the project documentation, including your own documents and the documentation generated by PHPdoc.
  337. `lib/` | Dedicated to foreign classes or libraries. Here, you can add the code that needs to be shared among your applications. The `model/` subdirectory stores the object model of the project (described in Chapter 8).
  338. `log/` | Stores the applicable log files generated directly by symfony. It can also contain web server log files, database log files, or log files from any part of the project. Symfony creates one log file per application and per environment (log files are discussed in Chapter 16).
  339. `plugins/` | Stores the plug-ins installed in the application (plug-ins are discussed in Chapter 17).
  340. `test/` | Contains unit and functional tests written in PHP and compatible with the symfony testing framework (discussed in Chapter 15). During the project setup, symfony automatically adds some stubs with a few basic tests.
  341. `web/` | The root for the web server. The only files accessible from the Internet are the ones located in this directory.
  342. #### Application Tree Structure
  343. The tree structure of all application directories is the same:
  344. apps/
  345. [application name]/
  346. config/
  347. i18n/
  348. lib/
  349. modules/
  350. templates/
  351. layout.php
  352. Table 2-2 describes the application subdirectories.
  353. Table 2-2 - Application Subdirectories
  354. Directory | Description
  355. ------------ | -----------
  356. `config/` | Holds a hefty set of YAML configuration files. This is where most of the application configuration is, apart from the default parameters that can be found in the framework itself. Note that the default parameters can still be overridden here if needed. You'll learn more about application configuration in the Chapter 5.
  357. `i18n/` | Contains files used for the internationalization of the application--mostly interface translation files (Chapter 13 deals with internationalization). You can bypass this directory if you choose to use a database for internationalization.
  358. `lib/` | Contains classes and libraries that are specific to the application.
  359. `modules/` | Stores all the modules that contain the features of the application.
  360. `templates/` | Lists the global templates of the application--the ones that are shared by all modules. By default, it contains a `layout.php` file, which is the main layout in which the module templates are inserted.
  361. >**NOTE**
  362. >The `i18n/`, `lib/`, and `modules/` directories are empty for a new application.
  363. The classes of an application are not able to access methods or attributes in other applications of the same project. Also note that hyperlinks between two applications of the same project must be in absolute form. You need to keep this last constraint in mind during initialization, when you choose how to divide your project into applications.
  364. #### Module Tree Structure
  365. Each application contains one or more modules. Each module has its own subdirectory in the `modules` directory, and the name of this directory is chosen during the setup.
  366. This is the typical tree structure of a module:
  367. apps/
  368. [application name]/
  369. modules/
  370. [module name]/
  371. actions/
  372. actions.class.php
  373. config/
  374. lib/
  375. templates/
  376. indexSuccess.php
  377. Table 2-3 describes the module subdirectories.
  378. Table 2-3 - Module Subdirectories
  379. Directory | Description
  380. ------------ | ------------
  381. `actions/` | Generally contains a single class file named `actions.class.php`, in which you can store all the actions of the module. You can also write different actions of a module in separate files.
  382. `config/` | Can contain custom configuration files with local parameters for the module.
  383. `lib/` | Stores classes and libraries specific to the module.
  384. `templates/` | Contains the templates corresponding to the actions of the module. A default template, called `indexSuccess.php`, is created during module setup.
  385. >**NOTE**
  386. >The `config/`, and `lib/` directories are empty for a new module.
  387. #### Web Tree Structure
  388. There are very few constraints for the `web` directory, which is the directory of publicly accessible files. Following a few basic naming conventions will provide default behaviors and useful shortcuts in the templates. Here is an example of a `web` directory structure:
  389. web/
  390. css/
  391. images/
  392. js/
  393. uploads/
  394. Conventionally, the static files are distributed in the directories listed in Table 2-4.
  395. Table 2-4 - Typical Web Subdirectories
  396. Directory | Description
  397. ---------- | -----------
  398. `css/` | Contains style sheets with a `.css` extension.
  399. `images/` | Contains images with a `.jpg`, `.png`, or `.gif` format.
  400. `js/` | Holds JavaScript files with a `.js` extension.
  401. `uploads/` | Can contain the files uploaded by the users. Even though the directory usually contains images, it is distinct from the images directory so that the synchronization of the development and production servers does not affect the uploaded images.
  402. >**NOTE**
  403. >Even though it is highly recommended that you maintain the default tree structure, it is possible to modify it for specific needs, such as to allow a project to run in a server with different tree structure rules and coding conventions. Refer to Chapter 19 for more information about modifying the file tree structure.
  404. Common Instruments
  405. ------------------
  406. A few techniques are used repeatedly in symfony, and you will meet them quite often in this book and in your own projects. These include parameter holders, constants, and class autoloading.
  407. ### Parameter Holders
  408. Many of the symfony classes contain a parameter holder. It is a convenient way to encapsulate attributes with clean getter and setter methods. For instance, the `sfRequest` class holds a parameter holder that you can retrieve by calling the `getParameterHolder()` method. Each parameter holder stores data the same way, as illustrated in Listing 2-14.
  409. Listing 2-14 - Using the `sfRequest` Parameter Holder
  410. [php]
  411. $request->getParameterHolder()->set('foo', 'bar');
  412. echo $request->getParameterHolder()->get('foo');
  413. => 'bar'
  414. Most of the classes using a parameter holder provide proxy methods to shorten the code needed for get/set operations. This is the case for the `sfRequest` object, so you can do the same as in Listing 2-14 with the code of Listing 2-15.
  415. Listing 2-15 - Using the `sfRequest` Parameter Holder Proxy Methods
  416. [php]
  417. $request->setParameter('foo', 'bar');
  418. echo $request->getParameter('foo');
  419. => 'bar'
  420. The parameter holder getter accepts a default value as a second argument. This provides a useful fallback mechanism that is much more concise than possible with a conditional statement. See Listing 2-16 for an example.
  421. Listing 2-16 - Using the Attribute Holder Getter's Default Value
  422. [php]
  423. // The 'foobar' parameter is not defined, so the getter returns an empty value
  424. echo $request->getParameter('foobar');
  425. => null
  426. // A default value can be used by putting the getter in a condition
  427. if ($request->hasParameter('foobar'))
  428. {
  429. echo $request->getParameter('foobar');
  430. }
  431. else
  432. {
  433. echo 'default';
  434. }
  435. => default
  436. // But it is much faster to use the second getter argument for that
  437. echo $request->getParameter('foobar', 'default');
  438. => default
  439. Some symfony core classes also use a parameter holder that support namespaces (thanks to the `sfNamespacedParameterHolder` class). If you specify a third argument to a setter or a getter, it is used as a namespace, and the parameter will be defined only within that namespace. Listing 2-17 shows an example.
  440. Listing 2-17 - Using the `sfUser` Parameter Holder Namespace
  441. [php]
  442. $user->setAttribute('foo', 'bar1');
  443. $user->setAttribute('foo', 'bar2', 'my/name/space');
  444. echo $user->getAttribute('foo');
  445. => 'bar1'
  446. echo $user->getAttribute('foo', null, 'my/name/space');
  447. => 'bar2'
  448. Of course, you can add a parameter holder to your own classes to take advantage of its syntax facilities. Listing 2-18 shows how to define a class with a parameter holder.
  449. Listing 2-18 - Adding a Parameter Holder to a Class
  450. [php]
  451. class MyClass
  452. {
  453. protected $parameterHolder = null;
  454. public function initialize($parameters = array())
  455. {
  456. $this->parameterHolder = new sfParameterHolder();
  457. $this->parameterHolder->add($parameters);
  458. }
  459. public function getParameterHolder()
  460. {
  461. return $this->parameterHolder;
  462. }
  463. }
  464. ### Constants
  465. You will not find any constants in symfony because by their very nature you
  466. can't change their value once they are defined. Symfony uses its own
  467. configuration object, called `sfConfig`, which replaces constants. It
  468. provides static methods to access parameters from everywhere. Listing 2-19
  469. demonstrates the use of `sfConfig` class methods.
  470. Listing 2-19 - Using the `sfConfig` Class Methods Instead of Constants
  471. [php]
  472. // Instead of PHP constants,
  473. define('FOO', 'bar');
  474. echo FOO;
  475. // symfony uses the sfConfig object
  476. sfConfig::set('foo', 'bar');
  477. echo sfConfig::get('foo');
  478. The sfConfig methods support default values, and you can call the sfConfig::set() method more than once on the same parameter to change its value. Chapter 5 discusses `sfConfig` methods in more detail.
  479. ### Class Autoloading
  480. Usually, when you use a class method or create an object in PHP, you need to
  481. include the class definition first:
  482. [php]
  483. include 'classes/MyClass.php';
  484. $myObject = new MyClass();
  485. On large projects with many classes and a deep directory structure,
  486. keeping track of all the class files to include and their paths can be time
  487. consuming. By providing an `spl_autoload_register()` function, symfony makes
  488. `include` statements unnecessary, and you can write directly:
  489. [php]
  490. $myObject = new MyClass();
  491. Symfony will then look for a `MyClass` definition in all files ending with `php` in one of the project's `lib/` directories. If the class definition is found, it will be included automatically.
  492. So if you store all your classes in `lib/` directories, you don't need to include classes anymore. That's why the symfony projects usually do not contain any `include` or `require` statements.
  493. >**NOTE**
  494. >For better performance, the symfony autoloading scans a list of directories (defined in an internal configuration file) during the first request. It then registers all the classes these directories contain and stores the class/file correspondence in a PHP file as an associative array. That way, future requests don't need to do the directory scan anymore. This is why you need to clear the cache every time you add or move a class file in your project by calling the `symfony cache:clear` command (except in the development environment, where symfony clears the cache once when it cannot find a class). You will learn more about the cache in Chapter 12, and about the autoloading configuration in Chapter 19.
  495. Summary
  496. -------
  497. Using an MVC framework forces you to divide and organize your code according to the framework conventions. Presentation code goes to the view, data manipulation code goes to the model, and the request manipulation logic goes to the controller. It makes the application of the MVC pattern both very helpful and quite restricting.
  498. Symfony is an MVC framework written in PHP 5. Its structure is designed to get the best of the MVC pattern, but with great ease of use. Thanks to its versatility and configurability, symfony is suitable for all web application projects.
  499. Now that you understand the underlying theory behind symfony, you are almost ready to develop your first application. But before that, you need a symfony installation up and running on your development server.