HelloWorld4回目

2018/01/30

アプリ作る。cakephp 3.5

composer create-project --prefer-dist cakephp/app MyApp2017

中に入る

cd MyApp2017/

sqlite3のdb作成

sqlite3 MyApp2017.db
sqlite> .tables
sqlite> .q

コンフィグでデータベースをsqlite3に。atomは好きなエディタで。

atom ./config/app.php
    Datasources => [
        default => [
            className => CakeDatabaseConnection,
            driver => CakeDatabaseDriverSqlite,
            persistent => false,
            database => MyApp2017.db,
            encoding => utf8,
            timezone => UTC,
            flags => [],
            cacheMetadata => true,
            log => false,

ここでサーバを立ち上げて確認する。

./bin/cake server

http://localhost:8765/にアクセス。databaseにつながっていることを確認。

ここでDBのテーブルを考える。
ログインしたユーザが書き込める掲示板という発想。

ユーザーテーブルを作ってみる。

./bin/cake bake migration CreateUsers name:string description:text created modified


/config/Migrationsフォルダに20170911144034_CreateUsers.phpファイルができる。

    public function change()
    {
        $table = $this->table(users);
        $table->addColumn(name, string, [
            default => null,
            limit => 255,
            null => false,
        ]);
        $table->addColumn(description, text, [
            default => null,
            null => false,
        ]);
        $table->addColumn(created, datetime, [
            default => null,
            null => false,
        ]);
        $table->addColumn(modified, datetime, [
            default => null,
            null => false,
        ]);
        $table->create();
    }

実際に作るには

./bin/cake migrations migrate

確認する。

sqlite3 MyApp2017.db
.tables
.schema

たしかにusersができている。idというautoincrementな主キーは自動で追加されるようだ。

次にUsersのモデル(テーブルとエンティティ)を作る。

./bin/cake bake model Users

これで

src/Model/Table/UsersTable.php

src/Model/Entity/User.php

ができた。

class UsersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable(users);
        $this->setDisplayField(name);
        $this->setPrimaryKey(id);

        $this->addBehavior(Timestamp);
    }

    /**
     * Default validation rules.
     *
     * @param CakeValidationValidator $validator Validator instance.
     * @return CakeValidationValidator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer(id)
            ->allowEmpty(id, create);

        $validator
            ->scalar(name)
            ->allowEmpty(name);

        $validator
            ->scalar(description)
            ->allowEmpty(description);

        return $validator;
    }
}
class User extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when * is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set * to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        * => true,
        id => false
    ];
}

調子に乗ってユーザーコントローラを作る。

./bin/cake bake controller Users

これで
/src/Controller/UsersController.php ができた。

<?php
namespace AppController;

use AppControllerAppController;

/**
 * Users Controller
 *
 * @property AppModelTableUsersTable $Users
 *
 * @method AppModelEntityUser[] paginate($object = null, array $settings = [])
 */
class UsersController extends AppController
{

    /**
     * Index method
     *
     * @return CakeHttpResponse|void
     */
    public function index()
    {
        $users = $this->paginate($this->Users);

        $this->set(compact(users));
        $this->set(_serialize, [users]);
    }

    /**
     * View method
     *
     * @param string|null $id User id.
     * @return CakeHttpResponse|void
     * @throws CakeDatasourceExceptionRecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            contain => []
        ]);

        $this->set(user, $user);
        $this->set(_serialize, [user]);
    }

    /**
     * Add method
     *
     * @return CakeHttpResponse|null Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $user = $this->Users->newEntity();
        if ($this->request->is(post)) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__(The user has been saved.));

                return $this->redirect([action => index]);
            }
            $this->Flash->error(__(The user could not be saved. Please, try again.));
        }
        $this->set(compact(user));
        $this->set(_serialize, [user]);
    }

    /**
     * Edit method
     *
     * @param string|null $id User id.
     * @return CakeHttpResponse|null Redirects on successful edit, renders view otherwise.
     * @throws CakeNetworkExceptionNotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            contain => []
        ]);
        if ($this->request->is([patch, post, put])) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__(The user has been saved.));

                return $this->redirect([action => index]);
            }
            $this->Flash->error(__(The user could not be saved. Please, try again.));
        }
        $this->set(compact(user));
        $this->set(_serialize, [user]);
    }

    /**
     * Delete method
     *
     * @param string|null $id User id.
     * @return CakeHttpResponse|null Redirects to index.
     * @throws CakeDatasourceExceptionRecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod([post, delete]);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__(The user has been deleted.));
        } else {
            $this->Flash->error(__(The user could not be deleted. Please, try again.));
        }

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


最後にtemplateをbakeする。

./bin/cake bake template Users

src/Template/Users/index.ctp

src/Template/Users/view.ctp

src/Template/Users/add.ctp

src/Template/Users/edit.ctp

が生成された。

このあたりでもう一度サーバーを立ち上げみてみる。

http://localhost:8765/users にアクセスするとユーザー一覧が出てくる。

続く。