Application Structure
3.4. APPLICATION COMPONENTS 63
// register "db" component using a configuration array 'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=demo', 'username' => 'root',
'password' => '', ],
// register "search" component using an anonymous function 'search' => function () {
return new app\components\SolrService;
], }, ]
Info: While you can register as many application components as you want, you should do this judiciously. Application com-ponents are like global variables. Using too many application components can potentially make your code harder to test and maintain. In many cases, you can simply create a local compo-nent and use it when needed.
3.4.1 Bootstrapping Components
As mentioned above, an application component will only be instantiated when it is being accessed the rst time. If it is not accessed at all during a request, it will not be instantiated. Sometimes, however, you may want to instantiate an application component for every request, even if it is not explicitly accessed. To do so, you may list its ID in the bootstrap property of the application.
For example, the following application conguration makes sure the log
component is always loaded:
[ 'bootstrap' => [ 'log', ],'components' => [
'log' => [
// configuration for "log" component ], ],
]
3.4.2 Core Application Components
Yii denes a set of core application components with xed IDs and default congurations. For example, the request component is used to collect in-formation about a user request and resolve it into a route; the db component
64 CHAPTER 3. APPLICATION STRUCTURE represents a database connection through which you can perform database queries. It is with help of these core application components that Yii appli-cations are able to handle user requests.
Below is the list of the predened core application components. You may congure and customize them like you do with normal application compo-nents. When you are conguring a core application component, if you do not specify its class, the default one will be used.
• assetManager: manages asset bundles and asset publishing. Please refer to the Managing Assets section for more details.
• db: represents a database connection through which you can perform DB queries. Note that when you congure this component, you must specify the component class as well as other required component prop-erties, such as yii\db\Connection::$dsn. Please refer to the Data Access Objects section for more details.
• errorHandler: handles PHP errors and exceptions. Please refer to the Handling Errors section for more details.
• formatter: formats data when they are displayed to end users. For example, a number may be displayed with thousand separator, a date may be formatted in long format. Please refer to the Data Formatting section for more details.
• i18n: supports message translation and formatting. Please refer to the Internationalization section for more details.
• log: manages log targets. Please refer to the Logging section for more details.
• mail: supports mail composing and sending. Please refer to the Mail-ing section for more details.
• response: represents the response being sent to end users. Please refer to the Responses section for more details.
• request: represents the request received from end users. Please refer to the Requests section for more details.
• session: represents the session information. This component is only available in Web applications. Please refer to the Sessions and Cook-ies section for more details.
• urlManager: supports URL parsing and creation. Please refer to the URL Parsing and Generation section for more details.
• user: represents the user authentication information. This component is only available in Web applications Please refer to the Authentica-tion secAuthentica-tion for more details.
• view: supports view rendering. Please refer to the Views section for more details.
3.5. CONTROLLERS 65
3.5 Controllers
Controllers are part of the MVC8 architecture. They are objects of classes extending from yii\base\Controller and are responsible for processing requests and generating responses. In particular, after taking over the control from applications, controllers will analyze incoming request data, pass them to models, inject model results into views, and nally generate outgoing responses.
3.5.1 Actions
Controllers are composed of actions which are the most basic units that end users can address and request for execution. A controller can have one or multiple actions.
The following example shows apostcontroller with two actions: viewand
create:
namespace app\controllers;
use Yii;
use app\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
class PostController extends Controller {
public function actionView($id) {
$model = Post::findOne($id);
if ($model === null) {
throw new NotFoundHttpException;
}
return $this->render('view', [ 'model' => $model,
} ]);
public function actionCreate() { $model = new Post;
if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [ 'model' => $model,
]);
} }
8http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
66 CHAPTER 3. APPLICATION STRUCTURE
}
In theviewaction (dened by the actionView()method), the code rst loads the model according to the requested model ID; If the model is loaded suc-cessfully, it will display it using a view namedview. Otherwise, it will throw an exception.
In the create action (dened by the actionCreate() method), the code is similar. It rst tries to populate the model using the request data and save the model. If both succeed it will redirect the browser to the view action with the ID of the newly created model. Otherwise it will display thecreate
view through which users can provide the needed input.
3.5.2 Routes
End users address actions through the so-called routes. A route is a string that consists of the following parts:
• a module ID: this exists only if the controller belongs to a non-application module;
• a controller ID: a string that uniquely identies the controller among all controllers within the same application (or the same module if the controller belongs to a module);
• an action ID: a string that uniquely identies the action among all actions within the same controller.
Routes take the following format:
ControllerID/ActionID
or the following format if the controller belongs to a module:
ModuleID/ControllerID/ActionID
So if a user requests with the URL http://hostname/index.php?r=site/index, theindex action in thesite controller will be executed. For more details on how routes are resolved into actions, please refer to the Routing and URL Generation section.
3.5.3 Creating Controllers
In Web applications, controllers should extend from yii\web\Controller or its child classes. Similarly in console applications, controllers should extend from yii\console\Controller or its child classes. The following code denes asite controller:
namespace app\controllers;
use yii\web\Controller;
class SiteController extends Controller {
}
3.5. CONTROLLERS 67