A factory is the definition of a class for a certain task. Symfony relies on factories for its core features such as the controller and session capabilities. For instance, when the framework needs to create a new request object, it searches in the factory definition for the name of the class to use for that purpose. The default factory definition for requests is sfWebRequest
, so symfony creates an object of this class in order to deal with requests. The great advantage of using a factory definition is that it is very easy to alter the core features of the framework: Just change the factory definition, and symfony will use your custom request class instead of its own.
The factory definitions are stored in the factories.yml
configuration file. Listing 17-13 shows the default factory definition file. Each definition is made of the name of an autoloaded class and (optionally) a set of parameters. For instance, the session storage factory (set under the storage:
key) uses a session_name
parameter to name the cookie created on the client computer to allow persistent sessions.
Listing 17-13 - Default Factories File, in myapp/config/factories.yml
cli:
controller:
class: sfConsoleController
request:
class: sfConsoleRequest
test:
storage:
class: sfSessionTestStorage
#all:
# controller:
# class: sfFrontWebController
#
# request:
# class: sfWebRequest
#
# response:
# class: sfWebResponse
#
# user:
# class: myUser
#
# storage:
# class: sfSessionStorage
# param:
# session_name: symfony
#
# view_cache:
# class: sfFileCache
# param:
# automaticCleaningFactor: 0
# cacheDir: %SF_TEMPLATE_CACHE_DIR%
The best way to change a factory is to create a new class inheriting from the default factory and to add new methods to it. For instance, the user session factory is set to the myUser
class (located in myapp/lib/
) and inherits from sfUser
. Use the same mechanism to take advantage of the existing factories. Listing 17-14 shows an example of a new factory for the request object.
Listing 17-14 - Overriding Factories
// Create a myRequest.class.php in an autoloaded directory,
// For instance in myapp/lib/
<?php
class myRequest extends sfRequest
{
// Your code here
}
// Declare this class as the request factory in factories.yml
all:
request:
class: myRequest