5.2. Action Controllers
By default, a segment of a URL path maps to a module, and another segment to an action. The action value is mapped to a method of the action controller class. By default, the value is title-cased, and the word action is appended. If no action is provided, the default action is assumed: actionIndex().
Example: News Action Controller
URI: http://www.domain.com/news/latest/title/2007 Module: news File: News.php Class: News Action: latest Method: actionLatest() Params: array(”title”, 2007)
modules/news/News.php
class News extends Trex_Module { public function actionLatest() { // echo $this->param[0] will output "title"; echo "Parameter 1: " . $this->param[0]; // echo $this->param[1] will output "2007"; echo "Parameter 2: " . $this->param[1]; // convert $this->param to an associative array $this->setParamKeys("sort_by", "year") // echo $this->param["sort_by"] will output "title"; echo "Parameter sort_by: " . $this->param["sort_by"]; // echo $this->param["date"] will output "2007"; echo "Parameter date: " . $this->param["date"]; } … }
Example: About Us Action Controller
URI: http://www.domain.com/about-us/ Module: about-us File: AboutUs.php Class: AboutUs Action: null Method: actionIndex() Params: array()
modules/about-us/AboutUs.php
class AboutUs extends Trex_Module { public function actionIndex() { … } }
5.2.1. Assigning default values to parameters
It is often helpful to be able to assign default values to parameters that aren’t passed, that way we don’t have to check if the parameter has been set or not.
To define your own default parameters, you can use the setParamValues() method:
- void setParamValues ( array param_values)
URI:
http://www.domain.com/news/latest/title/2007
News Action Controller:
class News extends Trex_Module { public function actionLatest() { // outputs array("title", 2007) print_r($this->param); // assign default values to parameters $this->setParamValues(array("title", "overwrite-me", "test")); // outputs array("title", 2007, "test") print_r($this->param); } }
It is not necessary to assign default values to parameters, however it is a very good practice. If a parameter doesn’t have a default value, you’ll need to use the isset() language construct to detect if the parameter has been set.
Note: A parameter sent via the URL will always overwrite a default parameter. That’s the whole point of using default values.
5.2.2. Assigning keys to parameters
You can convert the numeric array $this->param to an associative array using the setParamKeys() method:
- void setParamKeys ( array param_keys)
URI:
http://www.domain.com/news/latest/title/2007
News Action Controller:
class News extends Trex_Module { public function actionLatest() { // outputs array("title", 2007) print_r($this->param); // convert $this->param to an associative array $this->setParamKeys(array("sort_by", "year", "key_exists")); // outputs array("sort_by"=>"title", "year"=>2007, "key_exists"=>null) print_r($this->param); } }