The controller is part of the MVC pattern. It is an object that inherits the yii\base\Controller class and is responsible for processing requests and generating responses.
Specifically, after the controller takes over control from the application body, it will analyze the request data and transmit it to the model, transmit the model results to the view, and finally generate output response information.
action (Recommended learning: yii framework )
Controller consists of operations, it is the most basic foundation for executing end user requests requests A controller can have one or more operations.
The following example shows a controller post containing two actions view and 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, ]); } } }
In the operation view (defined as the actionView() method), the code is first based on Request the model ID to load the model. If the load is successful, the view named view will be rendered and displayed, otherwise an exception will be thrown.
In the operation create (defined as actionCreate() method), the code is similar. First fill in the request data into the model, and then save the model. If both are successful, it will jump to the newly created model with the ID view operation, otherwise the create view that provides user input is displayed.
The above is the detailed content of What is the use of yii framework controller. For more information, please follow other related articles on the PHP Chinese website!