PHP framework

운영자 | 기사입력 2007/02/01 [01:33]
>
필자의 다른기사 보기 인쇄하기 메일로 보내기 글자 크게 글자 작게
PHP framework
 
운영자   기사입력  2007/02/01 [01:33]

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

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
 
// Connecting, selecting database
$link = mysql_connect('localhost', 'myuser', 'mypassword');
mysql_select_db('blog_db', $link);
 
// Performing SQL query
$result = mysql_query('SELECT date, title FROM post', $link);
 
?>
 
<html>
  <head>
    <title>List of Posts</title>
  </head>
  <body>
   <h1>List of Posts</h1>
   <table>
     <tr><th>Date</th><th>Title</th></tr>
<?php
// Printing results in HTML
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "\t<tr>\n";
printf("\t\t<td> %s </td>\n", $row['date']);
printf("\t\t<td> %s </td>\n", $row['title']);
echo "\t</tr>\n";
}
?>
    </table>
  </body>
</html>
 
<?php
 
// Closing connection
mysql_close($link);
 
?>

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
 
 // Connecting, selecting database
 $link = mysql_connect('localhost', 'myuser', 'mypassword');
 mysql_select_db('blog_db', $link);
 
 // Performing SQL query
 $result = mysql_query('SELECT date, title FROM post', $link);
 
 // Filling up the array for the view
 $posts = array();
 while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
 {
    $posts[] = $row;
 }
 
 // Closing connection
 mysql_close($link);
 
 // Requiring the view
 require('view.php');
 
 ?>

The HTML code, containing template-like PHP syntax, is stored in a view script, as shown in Listing 2-3.

Listing 2-3 - The View Part, in view.php

<html>
  <head>
    <title>List of Posts</title>
  </head>
  <body>
    <h1>List of Posts</h1>
    <table>
      <tr><th>Date</th><th>Title</th></tr>
    <?php foreach ($posts as $post): ?>
      <tr>
        <td><?php echo $post['date'] ?></td>
        <td><?php echo $post['title'] ?></td>
      </tr>
    <?php endforeach; ?>
    </table>
  </body>
</html>

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
 
function getAllPosts()
{
  // Connecting, selecting database
  $link = mysql_connect('localhost', 'myuser', 'mypassword');
  mysql_select_db('blog_db', $link);
 
  // Performing SQL query
  $result = mysql_query('SELECT date, title FROM post', $link);
 
  // Filling up the array
  $posts = array();
  while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  {
     $posts[] = $row;
  }
 
  // Closing connection
  mysql_close($link);
 
  return $posts;
}
 
?>

The revised controller is presented in Listing 2-5.

Listing 2-5 - The Controller Part, Revised, in index.php

<?php
 
// Requiring the model
require_once('model.php');
 
// Retrieving the list of posts
$posts = getAllPosts();
 
// Requiring the view
require('view.php');
 
?>

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.

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.

Layer Separation Beyond MVC

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.

Other additional design patterns can make the coding experience even easier. The model, view, and controller layers can be further subdivided.

Database Abstraction

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.

An example of a MySQL-specific data access layer is presented in Listing 2-6, followed by a sample database abstraction layer in Listing 2-7.

Listing 2-6 - The Database Abstraction Part of the Model

<?php
 
function open_connection($host, $user, $password)
{
  return mysql_connect($host, $user, $password);
}
 
function close_connection($link)
{
  mysql_close($link);
}
 
function query_database($query, $database, $link)
{
  mysql_select_db($database, $link);
 
  return mysql_query($query, $link);
}
 
function fetch_results($result)
{
  return mysql_fetch_array($result, MYSQL_ASSOC);
}

Listing 2-7 - The Data Access Part of the Model
function getAllPosts()
{
  // Connecting to database
  $link = open_connection('localhost', 'myuser', 'mypassword');
 
  // Performing SQL query
  $result = query_database('SELECT date, title FROM post', 'blog_db', $link);
 
  // Filling up the array
  $posts = array();
  while ($row = fetch_results($result))
  {
     $posts[] = $row;
  }
 
  // Closing connection
  close_connection($link);
 
  return $posts;
}
 
?>

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.

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

<h1>List of Posts</h1>
<table>
<tr><th>Date</th><th>Title</th></tr>
<?php foreach ($posts as $post): ?>
  <tr>
    <td><?php echo $post['date'] ?></td>
    <td><?php echo $post['title'] ?></td>
  </tr>
<?php endforeach; ?>
</table>

Listing 2-9 - The View Logic Part of the View
<?php
 
$title = 'List of Posts';
$content = include('mytemplate.php');
 
?>

Listing 2-10 - The Layout Part of the View
<html>
  <head>
    <title><?php echo $title ?></title>
  </head>
  <body>
    <?php echo $content ?>
  </body>
</html>

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.

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

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
class weblogActions extends sfActions
{
  public function executeList()
  {
    $this->posts = PostPeer::doSelect(new Criteria());
  }
}
 
?>

Listing 2-12 - list Template, in myproject/apps/myapp/modules/weblog/templates/listSuccess.php
<h1>List of Posts</h1>
<table>
<tr><th>Date</th><th>Title</th></tr>
<?php foreach ($posts as $post): ?>
  <tr>
    <td><?php echo $post->getDate() ?></td>
    <td><?php echo $post->getTitle() ?></td>
  </tr>
<?php endforeach; ?>
</table>

Listing 2-13 - list View, in myproject/apps/myapp/modules/weblog/config/view.yml
listSuccess:
  metas: { title: List of Posts }

In addition, you will still need to define a layout, as shown in Listing 2-14, but it will be reused many times.

Listing 2-14 - Layout, in myproject/apps/myapp/templates/layout.php

<html>
  <head>
    <?php echo include_title() ?>
  </head>
  <body>
    <?php echo $sf_data->getRaw('sf_content') ?>
  </body>
</html>

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 singleton (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.

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).

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

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/
batch/
cache/
config/
data/
  sql/
doc/
lib/
  model/
log/
plugins/
test/
  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).
batch/ Contains PHP scripts called from a command line or a scheduler, to run batch processes.
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
      error.php
      error.txtdelete

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.

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
          validate/

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.
validate/ Dedicated to configuration files used for form validation (discussed in Chapter 10).

The config/, lib/, and validate/ 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/ Must 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.

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 sfResponse 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-15.

Listing 2-15 - Using the sfResponse Parameter Holder

$response->getParameterHolder()->set('foo', 'bar');
echo $response->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 sfResponse object, so you can do the same as in Listing 2-15 with the code of Listing 2-16.

Listing 2-16 - Using the sfResponse Parameter Holder Proxy Methods

$response->setParameter('foo', 'bar');
echo $response->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-17 for an example.

Listing 2-17 - Using the Attribute Holder Getter's Default Value

// The 'foobar' parameter is not defined, so the getter returns an empty value
echo $response->getParameter('foobar');
 => null
 
// A default value can be used by putting the getter in a condition
if ($response->hasParameter('foobar'))
{
  echo $response->getParameter('foobar');
}
else
{
  echo 'default';
}
 => default
 
// But it is much faster to use the second getter argument for that
echo $response->getParameter('foobar', 'default');
 => default

The parameter holders even support namespaces. 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-18 shows an example.

Listing 2-18 - Using the sfResponse Parameter Holder Namespace

$response->setParameter('foo', 'bar1');
$response->setParameter('foo', 'bar2', 'my/name/space');
echo $response->getParameter('foo');
 => 'bar1'
echo $response->getParameter('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-19 shows how to define a class with a parameter holder.

Listing 2-19 - Adding a Parameter Holder to a Class

class MyClass
{
  protected $parameter_holder = null;
 
  public function initialize ($parameters = array())
  {
    $this->parameter_holder = new sfParameterHolder();
    $this->parameter_holder->add($parameters);
  }
 
  public function getParameterHolder()
  {
    return $this->parameter_holder;
  }
}

Constants

Surprisingly, you will find very few constants in symfony. This is because constants have a major drawback in PHP: you can't change their value once they are defined. So symfony uses its own configuration object, called sfConfig, which replaces constants. It provides static methods to access parameters from everywhere. Listing 2-20 demonstrates the use of sfConfig class methods.

Listing 2-20 - Using the sfConfig Class Methods Instead of Constants

// Instead of PHP constants,
define('SF_FOO', 'bar');
echo SF_FOO;
// Symfony uses the sfConfig object
sfConfig::set('sf_foo', 'bar');
echo sfConfig::get('sf_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

Classically, when you use a class method or create an object in PHP, you need to include the class definition first.

include 'classes/MyClass.php';
$myObject = new MyClass();

But on large projects with many classes and a deep directory structure, keeping track of all the class files to include and their paths takes a lot of time. By providing an __autoload() function (or a spl_autoload_register() function), symfony makes include statements unnecessary, and you can write directly:

$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.

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 clear-cache command. 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.


트위터 트위터 페이스북 페이스북 카카오톡 카카오톡
기사입력: 2007/02/01 [01:33]  최종편집: ⓒ iwav