1. Yii2 完全CRUD + ログイン機能
  2. 各所で Yii1.1 との比較
  3. どこが破壊的変更か解説

までやります。


🟢 前提(Yii2は advanced じゃなく basic テンプレ想定)


🟢 ① Post モデル(Yii2)

models/Post.php

<?php

namespace app\models;

use yii\db\ActiveRecord;

// Postテーブルと紐づくActiveRecord
class Post extends ActiveRecord
{
    // テーブル名
    public static function tableName()
    {
        return 'post';
    }

    // バリデーション
    public function rules()
    {
        return [
            [['title', 'content'], 'required'],
            ['title', 'string', 'max' => 255],
        ];
    }

    // ラベル
    public function attributeLabels()
    {
        return [
            'title' => 'タイトル',
            'content' => '本文',
        ];
    }
}

🔥 Yii1.1との違い①

Yii1.1 Yii2
CActiveRecord yii\db\ActiveRecord
model()必要 不要
名前空間なし 名前空間必須
array()構文 []構文

🟢 ② PostController(完全CRUD)

controllers/PostController.php

<?php

namespace app\controllers;

use Yii;
use app\models\Post;
use yii\web\Controller;
use yii\filters\AccessControl;

class PostController extends Controller
{
    // アクセス制御
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // ログイン必須
                    ],
                ],
            ],
        ];
    }

    // 一覧
    public function actionIndex()
    {
        $posts = Post::find()->all();

        return $this->render('index', [
            'posts' => $posts,
        ]);
    }

    // 作成
    public function actionCreate()
    {
        $model = new Post();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    // 更新
    public function actionUpdate($id)
    {
        $model = Post::findOne($id);

        if (!$model) {
            throw new \yii\web\NotFoundHttpException();
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    // 削除
    public function actionDelete($id)
    {
        $model = Post::findOne($id);

        if ($model) {
            $model->delete();
        }

        return $this->redirect(['index']);
    }
}

🔥 Yii1.1との違い②

Yii1.1 Yii2
filters() behaviors()
accessRules() AccessControlクラス
findByPk findOne
$_POST request->post()
attributes代入 load()