The Front Controller
All web requests are handled by a single front controller, which is the unique entry point to the whole application in a given environment.
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
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:
- Define the core constants.
- Locate the symfony libraries.
- Load and initiate the core framework classes.
- Load the configuration.
- Decode the request URL to determine the action to execute and the request parameters.
- If the action does not exist, redirect to the 404 error action.
- Activate filters (for instance, if the request needs authentication).
- Execute the filters, first pass.
- Execute the action and render the view.
- Execute the filters, second pass.
- 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();
Actions
The Action Class
Actions are methods named executeActionName
of a class named moduleNameActions
inheriting from the sfActions
class, and grouped by modules. The action class of a module is stored in an actions.class.php
file, in the module's actions/
directory.
Listing 6-4 shows an example of an actions.class.php
file with only an index
action for the whole mymodule
module.
Listing 6-4 - Sample Action Class, in apps/myapp/modules/mymodule/actions/actions.class.php
class mymoduleActions extends sfActions
{
public function executeIndex()
{
...
}
public function executeList()
{
...
}
}
If the size of an action class grows too much, you probably need to do some refactoring and move some code to the model layer. Actions should often be kept short (not more than a few lines), and all the business logic should usually be in the model.
Retrieving Information in the Action
The action class offers a way to access controller-related information and the core symfony objects. Listing 6-8 demonstrates how to use them.
Listing 6-8 - sfActions
Common Methods
class mymoduleActions extends sfActions
{
public function executeIndex()
{
// Retrieving request parameters
$password = $this->getRequestParameter('password');
// Retrieving controller information
$moduleName = $this->getModuleName();
$actionName = $this->getActionName();
// Retrieving framework core objects
$request = $this->getRequest();
$userSession = $this->getUser();
$response = $this->getResponse();
$controller = $this->getController();
$context = $this->getContext();
// Setting action variables to pass information to the template
$this->setVar('foo', 'bar');
$this->foo = 'bar'; // Shorter version
}
}
The context singleton
You already saw, in the front controller, a call to sfContext::getInstance(). In an action, the getContext() method returns the same singleton. It is a very useful object that stores a reference to all the symfony core objects related to a given request, and offers an accessor for each of them:
sfController
: The controller object (->getController()
) sfRequest
: The request object (->getRequest()
) sfResponse
: The response object (->getResponse()
) sfUser
: The user session object (->getUser()
) sfDatabaseConnection
: The database connection (->getDatabaseConnection()
) sfLogger
: The logger object (->getLogger()
) sfI18N
: The internationalization object (->getI18N()
)
You can call the sfContext::getInstance()
singleton from any part of the code.
Action Termination
Various behaviors are possible at the conclusion of an action's execution. The value returned by the action method determines how the view will be rendered. Constants of the sfView
class are used to specify which template is to be used to display the result of the action.
If there is a default view to call (this is the most common case), the action should end as follows:
return sfView::SUCCESS;
Symfony will then look for a template called actionNameSuccess.php
. This is defined as the default action behavior, so if you omit the return
statement in an action method, symfony will also look for an actionNameSuccess.php
template. Empty actions will also trigger that behavior. See Listing 6-9 for examples of successful action termination.
Listing 6-9 - Actions That Will Call the indexSuccess.php
and listSuccess.php
Templates
public function executeIndex()
{
return sfView::SUCCESS;
}
public function executeList()
{
}
If there is an error view to call, the action should end like this:
return sfView::ERROR;
Symfony will then look for a template called actionNameError.php
.
To call a custom view, use this ending:
return 'MyResult';
Symfony will then look for a template called actionNameMyResult.php
.
If there is no view to call--for instance, in the case of an action executed in a batch process--the action should end as follows:
return sfView::NONE;
No template will be executed in that case.
Skipping to Another Action
The action class provides two methods to execute another action:
· If the action forwards the call to another action:
· $this->forward('otherModule', 'index');
· If the action results in a web redirection:
· $this->redirect('otherModule/index');
$this->redirect('http://www.google.com/');
The choice between a redirect or a forward is sometimes tricky. To choose the best solution, keep in mind that a forward is internal to the application and transparent to the user. As far as the user is concerned, the displayed URL is the same as the one requested. In contrast, a redirect is a message to the user's browser, involving a new request from it and a change in the final resulting URL.
There is a special kind of forward that is used very commonly. The forward404()
method forwards to a "page not found" action. This method is often called when a parameter necessary to the action execution is not present in the request (thus detecting a wrongly typed URL). Listing 6-12 shows an example of a show
action expecting an id
parameter.
Listing 6-12 - Use of the forward404()
Method
public function executeShow()
{
$article = ArticlePeer::retrieveByPK($this->getRequestParameter('id'));
if (!$article)
{
$this->forward404();
}
}
Repeating Code for Several Actions of a Module
There is another useful convention for when you need to repeat several statements in each action before the actual action execution. You can then extract them into the preExecute()
method of your action class. You can probably guess how to repeat statements after every action is executed: wrap them in a postExecute()
method. The syntax of these methods is shown in Listing 6-14.
Listing 6-14 - Using preExecute
, postExecute
, and Custom Methods in an Action Class
class mymoduleActions extends sfActions
{
public function preExecute()
{
// The code inserted here is executed at the beginning of each action call
...
}
public function executeIndex()
{
...
}
public function executeList()
{
...
$this->myCustomMethod(); // Methods of the action class are accessible
}
public function postExecute()
{
// The code inserted here is executed at the end of each action call
...
}
protected function myCustomMethod()
{
// You can also add your own methods, as long as they don't start with "execute"
// In that case, it's better to declare them as protected or private
...
}
User Session
Symfony automatically manages user sessions and is able to keep persistent data between requests for users. It uses the built-in PHP session-handling mechanisms and enhances them to make them more configurable and easier to use.
Accessing the User Session
The session object for the current user is accessed in the action with the getUser()
method and is an instance of the sfUser
class. This class contains a parameter holder that allows you to store any user attribute in it. This data will be available to other requests until the end of the user session, as shown in Listing 6-17. User attributes can store any type of data (strings, arrays, and associative arrays). They can be set for every individual user, even if that user is not identified.
Listing 6-17 - The sfUser
Object Can Hold Custom User Attributes Existing Across Requests
class mymoduleActions extends sfActions
{
public function executeFirstPage()
{
$nickname = $this->getRequestParameter('nickname');
// Store data in the user session
$this->getUser()->setAttribute('nickname', $nickname);
}
public function executeSecondPage()
{
// Retrieve data from the user session with a default value
$nickname = $this->getUser()->getAttribute('nickname', 'Anonymous Coward');
}
}
You can store objects in the user session, but it is strongly discouraged. This is because the session object is serialized between requests and stored in a file. When the session is deserialized, the class of the stored objects must already be loaded, and that's not always the case. In addition, there can be "stalled" objects if you store Propel objects.
Removing Data from the User Session
class mymoduleActions extends sfActions
{
public function executeRemoveNickname()
{
$this->getUser()->getAttributeHolder()->remove('nickname');
}
public function executeCleanup()
{
$this->getUser()->getAttributeHolder()->clear();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/d0bba1631363b441c1866803a255b3be.png)
Babylon English-English |
Wikipedia English - The Free Encycl... |
- Microcontroller, a computing device
- Memory controller, logic which manages the flow of data in a computer system
- Game controller, a device used for video games
- Controller (computing), a chip or extension card that interfaces with a peripheral device
- Comptroller, the accounting position
- Controller (control theory), in control theory
- Controller (irrigation), a device to automate irrigation systems
- Controller (control systems), a device used in Control systems
- Controller (orienteering), an organizer of orienteering events
- Model-view-controller, an architectural pattern used in software engineering
- Train Controller, an AC to DC converter used in model railways or track cars
- In fiction:
- Controller (Marvel Comics), a Marvel Comics supervillain
- Controllers (DC Comics), an alien race in DC comics
- Controller, in the Animorphs book and television series
- The Controller, an AI system in the Armored Core 3 video game
See more at Wikipedia.org... |
Babylon Dutch-English |
Telecommunication Standard Terms |
FOLDOC |
(1998-03-16)