CakePHPの美味しい始め方【増補版】

cakePHP3.5の美味しい始め方の研究中ノート。
ちょっと増強して書き直ししてみる。

「このノートのゴール」
 CakePHP3.5にACLとBootstrapを追加して動作する環境。
 ソース管理はBitbucket。

「前提」
 PHPとかMySQLとかcomposerとかは、すでに入ってること。
   ubuntu 16.04、PHP 7.2.2、MySQL 5.7.21をいれたものでテストしてます。

1.プロジェクト作る。
  プロジェクトを作りたいフォルダで

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

  とりあえず、apってのがプロジェクトの名前。任意で変える。

2.Apachのバーチャルホストの設定もする
  設定ファイルを作る。とりあえずxxxx.confにしてる。任意に変える
  ファイルの中身は環境に合わせて書く。

cd /etc/apache2/sites-available
vim xxxx.conf

  有効化しておく。

a2ensite xxxx.conf
apachectl configtest
service apache2 restart

3.DNSの設定もする
  必要に応じて設定しましょう。

4.gitに追加する
  追加したプロジェクトフォルダまで移動してGitの管理にしておきましょう

git init
git status
git add -A
git commit -m first_commit

5.Bitbucketにプロジェクト追加する
  https://bitbucket.org でリポジトリを新規に作る。
  「既にプロジェクトがあります。」のコマンドをサーバーで実行する。

git remote add origin git@bitbucket.org:USER_NAME/PROJECT_NAME.git
git push -u origin master

  USER_NAMEとPROJECT_NAMEは任意で変える。

6.mysqlにデータベース作る
  DATABASE_NAME、USER、PWDは任意で変える。

mysql -u root -p
CREATE DATABASE DATABASE_NAME CHARACTER SET utf8;
grant all privileges on DATABASE_NAME.* to USER@localhost identified by 'PWD';
FLUSH PRIVILEGES;

 ユーザー周りのテーブルも作る。

  CREATE TABLE `groups` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `name` varchar(100) NOT NULL,
   `created` datetime DEFAULT NULL,
   `modified` datetime DEFAULT NULL,
   PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  CREATE TABLE `users` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `username` varchar(255) NOT NULL,
   `password` varchar(255) DEFAULT NULL,
   `group_id` int(11) NOT NULL,
   `role` varchar(25) DEFAULT NULL,
   `created` datetime DEFAULT NULL,
   `modified` datetime DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `username` (`username`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

7.app.phpの設定をする

vim config/app.php

 SECURITY_SALTの文字列を書き換える。
 Datasourcesのところを任意に変更する

8.Composerで、ACL[cakephp/acl]とBootstrap[friendsofcake/bootstrap-ui]を追加する。

composer require cakephp/acl
composer require friendsofcake/bootstrap-ui

vim composer.json
requireの任意の場所に追記
"twbs/bootstrap": "3.*"

composer update

「vendor/twbs/bootstrap/dist」のファイルをwebroot/bootstrapにコピー

cp -r vendor/twbs/bootstrap/dist/* webroot/bootstrap/

9.「cakephp/acl」でアクセスコントロール(ACL)を行う設定をする

vim config/bootstrap.php
一番下にでも以下を追記
Plugin::load('Acl', ['bootstrap' => true]);

10.usersとgroupをbake allしとく

php bin/cake.php bake all users
php bin/cake.php bake all groups

11.PHPファイルを書き換える
1) UsersController.phpに追記

public function login() {
  if ($this->request->is('post')) {
    $user = $this->Auth->identify();
    if ($user) {
      $this->Auth->setUser($user);
      return $this->redirect($this->Auth->redirectUrl());
    }
    $this->Flash->error(__('Your username or password was incorrect.'));
  }
}
public function logout() {
  $this->Flash->success(__('Good-Bye'));
  $this->redirect($this->Auth->logout());
}

2)src/Templates/Users/login.ctp を新規作成

<?= $this->Form->create() ?>
  <fieldset>
    <legend><?= __('Login') ?></legend>
    <?= $this->Form->input('username') ?>
    <?= $this->Form->input('password') ?>
    <?= $this->Form->submit(__('Login')) ?>
  </fieldset>
<?= $this->Form->end() ?>

3)UsersTable.php、GroupTable.php を改造

initializeの中の $this->addBehavior('Timestamp'); という箇所を書き換える。

$this->addBehavior('Timestamp',['events' =>['Model.beforeSave' =>['created' => 'new','modified' => 'existing']]]);
$this->addBehavior('Acl.Acl', ['type' => 'requester']);

4)AppController.php に追記

$this->loadComponent('Auth', [
  'authorize' => ['Acl.Actions' => ['actionPath' => 'controllers/']],
  'loginAction' => ['plugin' => false,'controller' => 'Users','action' => 'login'],
  'loginRedirect' => ['plugin' => false,'controller' => 'Xxxxx','action' => 'index'],
  'logoutRedirect' => ['plugin' => false,'controller' => 'Users','action' => 'login'],
  'unauthorizedRedirect' => ['controller' => 'Users','action' => 'login','prefix' => false],
  'authError' => 'You are not authorized to access that location.',
  'flash' => ['element' => 'error']
]);

5)Group.php に追記

public function parentNode(){
 return null;
}

6)User.php に追記

use Cake\Auth\DefaultPasswordHasher;

public function parentNode(){
  if (!$this->id) {
    return null;
  }
  if (isset($this->group_id)) {
    $groupId = $this->group_id;
  } else {
    $Users = TableRegistry::get('Users');
    $user = $Users->find('all', ['fields' => ['group_id']])->where(['id' => $this->id])->first();
    $groupId = $user->group_id;
  }
  if (!$groupId) {
    return null;
  }
  return ['Groups' => ['id' => $groupId]];
}
protected function _setPassword($password){
  return (new DefaultPasswordHasher)-&gt;hash($password);
}

7)UsersController.php、GroupsController.php に追記

public function initialize(){
  parent::initialize();
  $this->Auth->allow();
}

8)bootstrapが使えるようAppView.php に追記

use BootstrapUI\View\UIView;
class AppView extends UIView{
 public function initialize(){
  parent::initialize();
  $this-&gt;layout = 'default';
 }
}

12.ACL系のテーブルを作成する

 php bin/cake.php Migrations.migrations migrate -p Acl
 php bin/cake.php acl_extras aco_sync

13.ユーザとグループ作成

 http://xxxxxx/groups/add
 Admin グループと、Userグループ作る。
 http://xxxxxx/users/add
 Adminグループのadmin作る。
 Userグループのuser作る

14.パーミッションの設定

 groupIDが1番の人がAdminだったとして、全アクセスつけるならこれ。
 php bin/cake.php acl grant Groups.1 controllers

 groupIDが2番の人は制限かけたいなら、とまず全アクセス剥奪する。
 php bin/cake.php acl deny Groups.2 controllers
 その後にアクセス可能なモノを1つづつ設定する。
 php bin/cake.php acl grant Groups.2 controllers/Xxxxx

15.UsersController.php、GroupsController.php の追記をコメントアウト

  これをコメントしておく。ユーザを追加する場合は、コメントはずす。
  $this->Auth->allow();


以上です。

この記事が気に入ったらサポートをしてみませんか?