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 taking over control from the application body, the controller analyzes the request data and transmits it to the model, transmits the model results to the view, and finally generates output response information. (Recommended learning: yii framework)
Action
The controller is composed of operations, which is the most basic unit for executing end-user 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, ]); } } }
Create controller
In Web applications, the controller should inherit yii\web\Controller or its subclasses. Similarly, in console applications, the controller inherits yii\console\Controller or its subclasses.
The following code defines a site controller:
namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { }
The above is the detailed content of How to define yii controller. For more information, please follow other related articles on the PHP Chinese website!