从 Yii 1.1 升级

安装

PHP 需求

命名空间

组件(Component)与对象(Object)

对象的配置

class MyClass extends \yii\base\Object
{
    public function __construct($param1, $param2, $config = [])
    {
        // ... 配置生效前的初始化过程

        parent::__construct($config);
    }

    public function init()
    {
        parent::init();

        // ...配置生效后的初始化过程
    }
}
$object = Yii::createObject([
    'class' => 'MyClass',
    'property1' => 'abc',
    'property2' => 'cde',
], [$param1, $param2]);

事件(Event)

$event = new \yii\base\Event;
$component->trigger($eventName, $event);
$component->on($eventName, $handler);
// 要解除相关句柄,使用 off 方法:
// $component->off($eventName, $handler);

路径别名(Path Alias)

视图(View)

echo $this->render('_item', ['item' => $item]);

模型(Model)

public function scenarios()
{
    return [
        'backend' => ['email', 'role'],
        'frontend' => ['email', '!role'],
    ];
}

控制器(Controller)

public function actionView($id)
{
    $model = \app\models\Post::findOne($id);
    if ($model) {
        return $this->render('view', ['model' => $model]);
    } else {
        throw new \yii\web\NotFoundHttpException;
    }
}

小部件(Widget)

use yii\widgets\Menu;
use yii\widgets\ActiveForm;

// 注意必须 **"echo"** 结果以显示内容
echo Menu::widget(['items' => $items]);

// 传递一个用于初始化对象属性的数组
$form = ActiveForm::begin([
    'options' => ['class' => 'form-horizontal'],
    'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
]);
... 表单输入栏都在这里 ...
ActiveForm::end();

主题(Theme)

控制台应用(Console Application)

国际化(I18N)

操作过滤器(Action Filters)

public function behaviors()
{
    return [
        'access' => [
            'class' => 'yii\filters\AccessControl',
            'rules' => [
                ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']],
            ],
        ],
    ];
}

前端资源(Assets)

助手类(Helpers)

表单

 <?php field($model, 'username') ?>
 <?php  field($model, 'password')->passwordInput() ?>
    

查询生成器(Query Builder)

$query = new \yii\db\Query();
$query->select('id, name')
      ->from('user')
      ->limit(10);

$command = $query->createCommand();
$sql = $command->sql;
$rows = $command->queryAll();

活动记录(Active Record)

// 检索所有 *活动的* 客户和订单,并以 ID 排序:
$customers = Customer::find()
    ->where(['status' => $active])
    ->orderBy('id')
    ->all();
class Customer extends \yii\db\ActiveRecord
{
    public function getOrders()
    {
        return $this->hasMany('Order', ['customer_id' => 'id']);
    }
}
$orders = $customer->getOrders()->andWhere('status=1')->all();
$customers = Customer::find()->asArray()->all();
public function init()
{
    parent::init();
    $this->status = self::STATUS_NEW;
}

用户及身份验证接口(IdentityInterface)

URL 管理

[
    'pattern' => 'post/
 
  /',
    'route' => 'post/index',
    'defaults' => ['page' => 1],
]
 

同时使用 Yii 1.1 和 2.x