Chapter 2 - Exploring Symfony's Code ==================================== 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. The MVC Pattern --------------- Symfony is based on the classic web design pattern known as the MVC architecture, which consists of three levels: * The Model represents the information on which the application operates--its business logic. * The View renders the model into a web page suitable for interaction with the user. * The Controller responds to user actions and invokes changes on the model or view as appropriate. Figure 2-1 illustrates the MVC pattern. 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. Figure 2-1 - The MVC pattern ![The MVC pattern](/images/book/F0201.png "The MVC pattern") ### MVC Layering 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. #### Flat Programming In a flat PHP file, displaying a list of database entries might look like the script presented in Listing 2-1. Listing 2-1 - A Flat Script [php] List of Posts

List of Posts

\n"; printf("\t\t\n", $row['date']); printf("\t\t\n", $row['title']); echo "\t\n"; } ?>
DateTitle
%s %s
That's quick to write, fast to execute, and impossible to maintain. The following are the major problems with this code: * There is no error-checking (what if the connection to the database fails?). * HTML and PHP code are mixed, even interwoven together. * The code is tied to a MySQL database. #### Isolating the Presentation 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. Listing 2-2 - The Controller Part, in `index.php` [php] List of Posts

List of Posts

DateTitle
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. 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. #### Isolating the Data Manipulation 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. Listing 2-4 - The Model Part, in `model.php` [php] **NOTE** >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. #### View Elements 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. Listing 2-8 - The Template Part of the View, in `mytemplate.php` [php]

List of Posts

DateTitle
Listing 2-9 - The View Logic Part of the View [php] <?php echo $title ?> #### Action and Front Controller 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. 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. #### Object Orientation 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. 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. 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. >**TIP** >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. ### Symfony's MVC Implementation 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: * Model layer * Database abstraction * Data access * View layer * View * Template * Layout * Controller layer * Front controller * Action 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. 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. 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. And the last thing is that the view logic can be easily translated as a simple configuration file, with no programming needed. Figure 2-2 - Symfony workflow ![Symfony workflow](/images/book/F0202.png "Symfony workflow") 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. Listing 2-11 - `list` Action, in `myproject/apps/myapp/modules/weblog/actions/actions.class.php` [php] posts = PostPeer::doSelect(new Criteria()); } } Listing 2-12 - `list` Template, in `myproject/apps/myapp/modules/weblog/templates/listSuccess.php` [php]

List of Posts

DateTitle
getDate() ?> getTitle() ?>
In addition, you will still need to define a layout, as shown in Listing 2-13, but it will be reused many times. Listing 2-13 - Layout, in `myproject/apps/myapp/templates/layout.php` [php] <?php include_slot('title') ?> 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. ### Symfony Core Classes The MVC implementation in symfony uses several classes that you will meet quite often in this book: * `sfController` is the controller class. It decodes the request and hands it to the action. * `sfRequest` stores all the request elements (parameters, cookies, headers, and so on). * `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. * The context (retrieved by `sfContext::getInstance()`) stores a reference to all the core objects and the current configuration; it is accessible from everywhere. You will learn more about these objects in Chapter 6. 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. >**NOTE** >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. Code Organization ----------------- 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. ### Project Structure: Applications, Modules, and Actions In symfony, a project is a set of services and operations available under a given domain name, sharing the same object model. 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. 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. 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). >**TIP** >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. 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. Figure 2-3 - Example of code organization ![Example of code organization](/images/book/F0203.png "Example of code organization") ### File Tree Structure All web projects generally share the same types of contents, such as the following: * A database, such as MySQL or PostgreSQL * Static files (HTML, images, JavaScript files, style sheets, and so on) * Files uploaded by the site users and administrators * PHP classes and libraries * Foreign libraries (third-party scripts) * Batch files (scripts to be launched by a command line or via a cron table) * Log files (traces written by the application and/or the server) * Configuration files 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. #### Root Tree Structure These are the directories found at the root of a symfony project: apps/ frontend/ backend/ cache/ config/ data/ sql/ doc/ lib/ model/ log/ plugins/ test/ bootstrap/ unit/ functional/ web/ css/ images/ js/ uploads/ Table 2-1 describes the contents of these directories. Table 2-1 - Root Directories Directory | Description ---------- | ------------ `apps/` | Contains one directory for each application of the project (typically, `frontend` and `backend` for the front and back office). `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. `config/` | Holds the general configuration of the project. `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. `doc/` | Stores the project documentation, including your own documents and the documentation generated by PHPdoc. `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). `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). `plugins/` | Stores the plug-ins installed in the application (plug-ins are discussed in Chapter 17). `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. `web/` | The root for the web server. The only files accessible from the Internet are the ones located in this directory. #### Application Tree Structure The tree structure of all application directories is the same: apps/ [application name]/ config/ i18n/ lib/ modules/ templates/ layout.php Table 2-2 describes the application subdirectories. Table 2-2 - Application Subdirectories Directory | Description ------------ | ----------- `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. `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. `lib/` | Contains classes and libraries that are specific to the application. `modules/` | Stores all the modules that contain the features of the application. `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. >**NOTE** >The `i18n/`, `lib/`, and `modules/` directories are empty for a new application. 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. #### Module Tree Structure 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. This is the typical tree structure of a module: apps/ [application name]/ modules/ [module name]/ actions/ actions.class.php config/ lib/ templates/ indexSuccess.php Table 2-3 describes the module subdirectories. Table 2-3 - Module Subdirectories Directory | Description ------------ | ------------ `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. `config/` | Can contain custom configuration files with local parameters for the module. `lib/` | Stores classes and libraries specific to the module. `templates/` | Contains the templates corresponding to the actions of the module. A default template, called `indexSuccess.php`, is created during module setup. >**NOTE** >The `config/`, and `lib/` directories are empty for a new module. #### Web Tree Structure 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: web/ css/ images/ js/ uploads/ Conventionally, the static files are distributed in the directories listed in Table 2-4. Table 2-4 - Typical Web Subdirectories Directory | Description ---------- | ----------- `css/` | Contains style sheets with a `.css` extension. `images/` | Contains images with a `.jpg`, `.png`, or `.gif` format. `js/` | Holds JavaScript files with a `.js` extension. `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. >**NOTE** >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. Common Instruments ------------------ 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. ### Parameter Holders 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. Listing 2-14 - Using the `sfRequest` Parameter Holder [php] $request->getParameterHolder()->set('foo', 'bar'); echo $request->getParameterHolder()->get('foo'); => 'bar' 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. Listing 2-15 - Using the `sfRequest` Parameter Holder Proxy Methods [php] $request->setParameter('foo', 'bar'); echo $request->getParameter('foo'); => 'bar' 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. Listing 2-16 - Using the Attribute Holder Getter's Default Value [php] // The 'foobar' parameter is not defined, so the getter returns an empty value echo $request->getParameter('foobar'); => null // A default value can be used by putting the getter in a condition if ($request->hasParameter('foobar')) { echo $request->getParameter('foobar'); } else { echo 'default'; } => default // But it is much faster to use the second getter argument for that echo $request->getParameter('foobar', 'default'); => default 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. Listing 2-17 - Using the `sfUser` Parameter Holder Namespace [php] $user->setAttribute('foo', 'bar1'); $user->setAttribute('foo', 'bar2', 'my/name/space'); echo $user->getAttribute('foo'); => 'bar1' echo $user->getAttribute('foo', null, 'my/name/space'); => 'bar2' 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. Listing 2-18 - Adding a Parameter Holder to a Class [php] class MyClass { protected $parameterHolder = null; public function initialize($parameters = array()) { $this->parameterHolder = new sfParameterHolder(); $this->parameterHolder->add($parameters); } public function getParameterHolder() { return $this->parameterHolder; } } ### Constants You will not find any constants in symfony because by their very nature you can't change their value once they are defined. Symfony uses its own configuration object, called `sfConfig`, which replaces constants. It provides static methods to access parameters from everywhere. Listing 2-19 demonstrates the use of `sfConfig` class methods. Listing 2-19 - Using the `sfConfig` Class Methods Instead of Constants [php] // Instead of PHP constants, define('FOO', 'bar'); echo FOO; // symfony uses the sfConfig object sfConfig::set('foo', 'bar'); echo sfConfig::get('foo'); 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. ### Class Autoloading Usually, when you use a class method or create an object in PHP, you need to include the class definition first: [php] include 'classes/MyClass.php'; $myObject = new MyClass(); On large projects with many classes and a deep directory structure, keeping track of all the class files to include and their paths can be time consuming. By providing an `spl_autoload_register()` function, symfony makes `include` statements unnecessary, and you can write directly: [php] $myObject = new MyClass(); 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. 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. >**NOTE** >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. Summary ------- 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. 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. 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.