Yii implements the model-view-controller (MVC) design pattern, which is widely adopted in web and other application programming. MVC aims to separate business logic from user interface considerations, allowing developers to more easily change individual components of an application without affecting, or even touching, another.
In MVC, the model represents the information (the data) and the business rules to which the data must adhere. The view contains elements of the user interface, such as text, images, and form elements. The controller manages the communication between the model and the view, acting as an agent.
Besides implementing the MVC design pattern, Yii also introduces a front-controller, called application. The front-controller encapsulates the execution context for the processing of a request. This means that the front-controller collects information about a user request, and then dispatches it to an appropriate controller for actual handling of that request. In other words, the front-controller is the primary application manager, handling all requests and delegating action accordingly.
The following diagram shows the static structure of a Yii application:
The following diagram shows a typical workflow of a Yii application handling a user request:
- A user makes a request of the URL
http://www.example.com/index.php?r=post/show&id=1
. The Web server handles the request by executing the bootstrap scriptindex.php
. - The bootstrap script creates an [[Application|yii\web\Application]] instance and runs it.
- The Application instance obtains the detailed user request information from an application component named
request
. - The application determines which controller and which action of that controller was requested.
This is accomplished with the help of an application component named
urlManager
. For this example, the controller ispost
, which refers to thePostController
class; and the action isshow
, whose actual meaning is determined by the controller. - The application creates an instance of the requested controller to further handle the users request.
The controller determines that the action
show
refers to a method namedactionShow
in the controller class. It then creates and executes filters (e.g. access control, benchmarking) associated with this action. The action is then executed, if execution is allowed by the filters (e.g., if the user has permission to execute that action). - The action creates a
Post
model instance, using the underlying database table, where the ID value of the corresponding record is1
. - The action renders a view named
show
, providing to the view thePost
model instance. - The view reads the attributes of the
Post
model instance and displays the values of those attributes. - The view executes some widgets.
- The view rendering result -the output from the previous steps- is embedded in a layout to create a complete page.
- The action completes the view rendering and displays the result to the user.