Installing Yii from an archive file involves three steps:

  • Download the archive file from yiiframework.com.
  • Unpack the downloaded file to a Web-accessible folder.
  • Modify the config/web.php file by entering a secret key for the cookieValidationKey configuration item (this is done automatically if you are installing Yii using Composer):
'cookieValidationKey' => 'enter your secret key here',
  • 使用浏览器访问/basic/web/index.php,如果有报错则根据报错信息解决错误。
  • 执行php yii server运行yii的内置Web Server,默认运行在http://localhost:8080/

You should see the above “Congratulations!” page in your browser.

sudo apt install php7.0-mbstring


Yii 应用参照模型-视图-控制器 (MVC) 设计模式来组织。

除了 MVC, Yii 应用还有以下部分:

  • 入口脚本:终端用户能直接访问的 PHP 脚本, 负责启动一个请求处理周期。
  • 应用:能全局范围内访问的对象, 管理协调组件来完成请求.
  • 应用组件:在应用中注册的对象, 提供不同的功能来完成请求。
  • 模块:包含完整 MVC 结构的独立包, 一个应用可以由多个模块组建。
  • 过滤器:控制器在处理请求之前或之后 需要触发执行的代码。
  • 小部件:可嵌入到视图中的对象, 可包含控制器逻辑,可被不同视图重复调用。

下面的示意图展示了 Yii 应用的静态结构:


  1. 终端访问入口脚本,应用接收到一个包含ControllerID/ActionID的URL
  2. 控制器从应用主体接管控制后会分析请求数据并传送到模型,传送模型结果到视图。
  3. 默认会使用@app/views/layouts/main.php布局文件,同时使布局到渲染结果中。



Creating an Action

For the “Hello” task, you will create a say action that reads a message parameter from the request and displays that message back to the user. If the request does not provide a message parameter, the action will display the default “Hello” message.

Info: Actions are the objects that end users can directly refer to for execution. Actions are grouped by controllers. The execution result of an action is the response that an end user will receive.

Actions must be declared in controllers. For simplicity, you may declare the say action in the existing SiteController. This controller is defined in the class file controllers/SiteController.php. Here is the start of the new action:

render('say', ['message' => $message]);


public function actionIndex()
    $this->layout = 'bjut';//用于渲染的布局文件
    return $this->render('index');//用于渲染的视图文件



When it comes to naming your actions, you should understand how Yii treats action IDs. Action IDs are always referenced in lower case. If an action ID requires multiple words, they will be concatenated by dashes (e.g., `create-comment`). Action method names are mapped to action IDs by removing any dashes from the IDs, capitalizing the first letter in each word, and prefixing the resulting string with `action`. For example, the action ID `create-comment` corresponds to the action method name `actionCreateComment`.

Creating a View

Views are scripts you write to generate a response’s content. For the “Hello” task, you will create a say view that prints the message parameter received from the action method:

use yii\helpers\Html;
<?= Html::encode($message) ?>


Like actions, controllers also have IDs that uniquely identify them in an application. Controller IDs use the same naming rules as action IDs. Controller class names are derived from controller IDs by removing dashes from the IDs, capitalizing the first letter in each word, and suffixing the resulting string with the word Controller. For example, the controller ID post-comment corresponds to the controller class name PostCommentController.



return $this->render('index', array('message' => '1222'));


<?php echo ($message); ?>


To get request parameters, you can call get() and post() methods of the request component. They return the values of $_GET and $_POST, respectively. For example,

<input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />

否则会引发Unable to verify your data submission.异常。

$request = Yii::$app->request;

$get = $request->get();
// equivalent to: $get = $_GET;

$id = $request->get('id');
// equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : null;

$id = $request->get('id', 1);
// equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : 1;

$post = $request->post();
// equivalent to: $post = $_POST;

$name = $request->post('name');
// equivalent to: $name = isset($_POST['name']) ? $_POST['name'] : null;

$name = $request->post('name', '');
// equivalent to: $name = isset($_POST['name']) ? $_POST['name'] : '';

Info: Instead of directly accessing $_GET and $_POST to retrieve the request parameters, it is recommended that you get them via the request component as shown above. This will make writing tests easier because you can create a mock request component with faked request data.


To achieve this goal, besides creating an action and two views, you will also create a model.
Through this tutorial, you will learn how to:

  • create a model to represent the data entered by a user through a form,
  • declare rules to validate the data entered,
  • build an HTML form in a view.


The data to be requested from the user will be represented by an EntryForm model class as shown below and saved in the file models/EntryForm.php. Please refer to the Class Autoloading section for more details about the class file naming convention.

namespace app\models;
use Yii;
use yii\base\Model;
class EntryForm extends Model
    public $name;
    public $email;
    public function rules()
        return [[['name', 'email'], 'required'], ['email', 'email'], ];


Next, you’ll need to create an entry action in the site controller that will use the new model.

namespace app\models;
use Yii;
use yii\base\Model;
use app\models\EntryForm;
class SiteController extends Controller{
	// ...existing code...
	public function actionEntry(){
$model = new EntryForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            // valid data received in $model

            // do something meaningful here about $model ...

            return $this->render('entry-confirm', ['model' => $model]);
        } else {
            // either the page is initially displayed or there is some validation error
            return $this->render('entry', ['model' => $model]);


> The view uses a powerful widget called ActiveForm to build the HTML form. The begin() and end() methods of the widget render the opening and closing form tags, respectively. Between the two method calls, input fields are created by the field() method. The first input field is for the “name” data, and the second for the “email” data. After the input fields, the yii\helpers\Html::submitButton() method is called to generate a submit button.

use yii\helpers\Html;
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'name') ?>
<?=$form->field($model, 'email') ?>
<div class="form-group">
<?=Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>


Configuring a DB Connection

Before proceeding, make sure you have installed both the PDO PHP extension and the PDO driver for the database you are using (e.g. pdo_mysql for MySQL). This is a basic requirement if your application uses a relational database.

With those installed, open the file config/db.php and change the parameters to be correct for your database. By default, the file contains the following:

return [
    'class' =>  'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2basic',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',

The DB connection configured above can be accessed in the application code via the expression Yii::$app->db.

Data Access Object


public function actionTestdb()
        $connection = Yii::$app->db; //连接
        $sql = "SELECT * FROM `admin` ORDER BY `admin_fname` DESC";//执行SQL查询
        $command = $connection->createCommand($sql);
        $result = $command->queryAll();
        // return $this->render('test');


找到'bootstrap' => ['log'],一行,改为:

'bootstrap' => ['debug'],
'modules' => [
    'debug' => [
        'class' => 'yii\debug\Module',
        'allowedIPs' => ['', '', '::1'],









发表回复/Leave a Reply

您的电子邮箱地址不会被公开。/Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.