Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
$ cd Sites
$ composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic yii2-basic-app
$ cd yii2-basic-app
$ pstorm .

ストームで ⌥ + F12

$ php -S 127.0.0.1:8080 -t web

リモートの人対応

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        'allowedIPs' => [
            '*',
        ],
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module'; // こっちも上みたいにする
}

http://localhost:8080/

http://localhost:8080/index.php?r=site%2Fabout ←ダサい

じっけん

yiisoft/yii2 から routing を検索 → UrlManager

$application = new yii\web\Application($config);
$application->urlManager->enablePrettyUrl = true;
$application->urlManager->showScriptName = false;
$application->run();

ほんとは config/web.php にこう

$config = [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
        ],

http://localhost:8080/index.php/site/about

$config = [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],

http://localhost:8080/site/about

PHPビルトインサーバーすげぇ

rules で独自ルーティングもできるよ

Apache用はこれで

RewriteEngine on
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]

config = yii\base\Application 構造が同じ。これだいじ

Arrayの定義からComponentを作るスタイル

views/layouts.php で確認

            NavBar::begin([
                'brandLabel' => 'My Company',
                'brandUrl' => Yii::$app->homeUrl,
                'options' => [
                    'class' => 'navbar-inverse navbar-fixed-top',
                ],
            ]);
            echo Nav::widget([
                'options' => ['class' => 'navbar-nav navbar-right'],
                'items' => [
                    ['label' => 'Home', 'url' => ['/site/index']],
                    ['label' => 'About', 'url' => ['/site/about']],
                    ['label' => 'Contact', 'url' => ['/site/contact']],
                    Yii::$app->user->isGuest ?
                        ['label' => 'Login', 'url' => ['/site/login']] :
                        ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
                            'url' => ['/site/logout'],
                            'linkOptions' => ['data-method' => 'post']],
                ],
            ]);
            NavBar::end();

HTMLウィジェットだいたいこんな感じ

Giiやる

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

http://localhost:8080/gii

config/db.php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=blogdemo',
    'username' => 'blogdemo',
    'password' => 'blogdemo',
    'charset' => 'utf8',
];
$ ./yii migrate/create blogdemo
<?php

use yii\db\Schema;

class m140610_081535_blogdemo extends \yii\db\Migration
{
    public function up()
    {
        $options = 'DEFAULT CHARSET=utf8'; // MySQLのデフォルトが変な人対応

        $this->createTable('user', [
            'id' => 'pk',
            'username' => Schema::TYPE_STRING . ' NOT NULL',
            'plain_password' => Schema::TYPE_STRING . ' NOT NULL',
            'access_token' => Schema::TYPE_STRING . ' NOT NULL',
            'auth_key' => Schema::TYPE_STRING . ' NOT NULL',
        ], $options);

        $this->createTable('entry', [
            'id' => 'pk',
            'title' => Schema::TYPE_STRING . ' NOT NULL',
            'body' => Schema::TYPE_TEXT,
            'author_id' => Schema::TYPE_INTEGER  . ' NOT NULL',
            'create_time' => Schema::TYPE_DATETIME . ' NOT NULL',
            'update_time' => Schema::TYPE_DATETIME . ' NOT NULL',
        ], $options);

        $this->addForeignKey('fk_entry_author', 'entry', 'author_id', 'user', 'id', 'RESTRICT');

        return true;
    }

    public function down()
    {
        $this->dropTable('entry');
        $this->dropTable('user');

        return true;
    }
}
$ ./yii migrate/up
$ ./yii migrate/down
$ ./yii migrate/up

http://localhost:8080/gii でモデル生成 x2

userテーブルはいったんWebUserで作成しよう

CRUDでUserController

http://localhost:8080/user/

もうだいたいつかえる。ちょっとついか。

    /**
     * @return string
     */
    public function getHashedPassword()
    {
        return md5($this->plain_password);
    }

views/user/view.php

    <p>
        <?= $model->getHashedPassword() ?>
    </p>
    <p>
        <?= $model->hashedPassword ?>
    </p>

⌥ + ENTER するよね

/**
 * This is the model class for table "user".
 * 略
 * 
 * @property string hashedPassword
 */
class WebUser extends \yii\db\ActiveRecord

プロパティになったってことは

view.php

    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'username',
            // 'plain_password',
            'hashedPassword',
            'access_token',
            'auth_key',
        ],
    ]) ?>

index.php

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'username',
            // 'plain_password',
            'hashedPassword',
            'access_token',
            'auth_key',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

http://localhost:8080/entry/

いろいろカスタマイズが必要

_form.php

    <?php $users = WebUser::find()->orderBy('id')->all(); ?>
    <?= $form->field($model, 'author_id')->dropDownList(
        ArrayHelper::map($users, 'id', 'username')
    ) ?>

models/Entry.php

    public function rules()
    {
        // 日時はバリデーションしないで自動で入れたい
        return [
            [['title', 'author_id'], 'required'],
            [['body'], 'string'],
            [['author_id'], 'integer'],
            [['title'], 'string', 'max' => 255]
        ];
    }

    /**
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            return false;
        }

        $now = date('Y-m-d H:i:s');
        if ($insert) {
            $this->create_time = $now;
        }
        $this->update_time = $now;

        return true;
    }

Yiiはオブジェクトにイベントリスナーを挿すのが一般化されてて、ビヘイビアでやることもできるよ。

    public function behaviors()
    {
        return [
            'timestamp' => [
                // ここオブジェクト生成のパラメータ。Applicationと同じ
                'class' => TimestampBehavior::className(), // クラス名だけは特別
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
                ],
                'value' => function() {
                    return date('Y-m-d H:i:s');
                },
            ],
        ];
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.