O Controlador de Frente

Todas as requisições web são gerenciadas por um unico Controle de Frente, que é o único ponto de entrada para toda uma aplicação em um dado ambiente.

Quando o controlador de frente recebe uma requisição, ele usa um sistema de roteamento para casar a URL digitada(ou clicada) pelo usuario com uma ação e um módulo. Como exemplo, a seguinte URL chama o script index.php( este é o controlador de frente) e que vai ser entendida como uma chamada para a ação myAction do módulo mymodule:

    http://localhost/index.php/mymodule/myAction

When the front controller receives a request, it uses the routing system to match an action name and a module name with the URL typed (or clicked) by the user. For instance, the following request URL calls the index.php script (that's the front controller) and will be understood as a call to the action myAction of the module mymodule:

    http://localhost/index.php/mymodule/myAction

If you are not interested in symfony's internals, that's all that you need to know about the front controller. It is an indispensable component of the symfony MVC architecture, but you will seldom need to change it. So you can jump to the next section unless you really want to know about the guts of the front controller.

The Front Controller's Job in Detail

The front controller does the dispatching of the request, but that means a little more than just determining the action to execute. In fact, it executes the code that is common to all actions, including the following:

  1. Define the core constants.
  2. Locate the symfony libraries.
  3. Load and initiate the core framework classes.
  4. Load the configuration.
  5. Decode the request URL to determine the action to execute and the request parameters.
  6. If the action does not exist, redirect to the 404 error action.
  7. Activate filters (for instance, if the request needs authentication).
  8. Execute the filters, first pass.
  9. Execute the action and render the view.
  10. Execute the filters, second pass.
  11. Output the response.

The Default Front Controller

The default front controller, called index.php and located in the web/ directory of the project, is a simple PHP file, as shown in Listing 6-1.

Listing 6-1 - The Default Production Front Controller

    <?php

    define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
    define('SF_APP',         'myapp');
    define('SF_ENVIRONMENT', 'prod');
    define('SF_DEBUG',       false);
    require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.    config'.DIRECTORY_SEPARATOR. 'config.php');

    sfContext::getInstance()->getController()->dispatch();
   ?>

The constants definition corresponds to the first step described in the previous section. Then the front controller includes the application config.php, which takes care of steps 2 through 4. The call to the dispatch() method of the sfController object (which is the core controller object of the symfony MVC architecture) dispatches the request, taking care of steps 5 through 7. The last steps are handled by the filter chain, as explained later in this chapter.

Calling Another Front Controller to Switch the Environment

One front controller exists per environment. As a matter of fact, it is the very existence of a front controller that defines an environment. The environment is defined in the SF_ENVIRONMENT constant.

To change the environment in which you're browsing your application, just choose another front controller. The default front controllers available when you create a new application with the symfony init-app task are index.php for the production environment and myapp_dev.php for the development environment (provided that your application is called myapp). The default mod_rewrite configuration will use index.php when the URL doesn't contain a front controller script name. So both of these URLs display the same page (mymodule/index) in the production environment:

    http://localhost/index.php/mymodule/index
    http://localhost/mymodule/index

and this URL displays that same page in the development environment:

    http://localhost/myapp_dev.php/mymodule/index

Creating a new environment is as easy as creating a new front controller. For instance, you may need a staging environment to allow your customers to test the application before going to production. To create this staging environment, just copy web/myapp_dev.php into web/myapp_staging.php, and change the value of the SF_ENVIRONMENT constant to staging. Now, in all the configuration files, you can add a new staging: section to set specific values for this environment, as shown in Listing 6-2.

Listing 6-2 - Sample app.yml with Specific Settings for the Staging Environment

    staging:
      mail:
        webmaster:    dummy@mysite.com
        contact:      dummy@mysite.com
    all:
      mail:
        webmaster:    webmaster@mysite.com
        contact:      contact@mysite.com

If you want to see how the application reacts in this new environment, call the related front controller:

    http://localhost/myapp_staging.php/mymodule/index

Batch Files

You may want to execute a script from the command line (or via a cron table) with access to all the symfony classes and features, for instance to launch batch e-mail jobs or to periodically update your model through a process-intensive calculation. For such a script, you need to include the same lines as in a front controller at the beginning. Listing 6-3 shows an example of the beginning of a batch script.

Listing 6-3 - Sample Batch Script

    <?php

    define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
    define('SF_APP',         'myapp');
    define('SF_ENVIRONMENT', 'prod');
    define('SF_DEBUG',       false);

    require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');

    // add code here

    ?>

You can see that the only missing line is the call to the dispatch() method of the sfController object, which can be used only with a web server, not in a batch process. Defining an application and an environment gives you access to a specific configuration. Including the application config.php initiates the context and the autoloading.

**TIP** The symfony CLI offers an init-batch task, which automatically creates a skeleton similar to the one in Listing 6-3 in the batch/ directory. Just pass it an application name, an environment name, and a batch name as arguments.

« Anterior Índice do Capitulo Seguinte »