フォーム要素にラベルを出さない

echo $this->Form->input('body', array('rows' => '3', 'value' => 'hoge', 'label' => false));

ログ設定

app/Config/bootstrap.php

App::uses('CakeLog', 'Log');
CakeLog::config('debug', array(
    'engine' => 'File',
    'types' => array('notice', 'info', 'debug'),
    'file' => 'debug',
));
CakeLog::config('error', array(
    'engine' => 'File',
    'types' => array('warning', 'error', 'critical', 'alert', 'emergency'),
    'file' => 'error',
));

ログ出力場所

  • app/tmp/logs/debug.log
  • app/tmp/logs/error.log

ログ出力方法

CakeLog::write('debug', $hoge);
CakeLog::write('error', $hoge);

デバッグレベル

app/Config/core.php

Configure::write('debug', 2);

認証

CREATE TABLE

CREATE TABLE users (
    id       INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50),
    password VARCHAR(255),
    role     VARCHAR(20),
    created  DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);

Model

app/Model/User.php

<?php
class User extends AppModel {
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A password is required'
            )
        ),
        'role' => array(
            'valid' => array(
                'rule' => array('inList', array('admin', 'author')),
                'message' => 'Please enter a valid role',
                'allowEmpty' => false
            )
        )
    );
}

Controller

app/Model/UsersController.php

<?php
class UsersController extends AppController {

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add');
    }

    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
    }

    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
            unset($this->request->data['User']['password']);
        }
    }

    public function delete($id = null) {
        $this->request->onlyAllow('post');

        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

}

AppController

public $components = array(
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'dashboard', 'action' => 'index'),
        'authorize' => array('Controller'), // isAuthorized によって承認判定
    )
);

// 現在のユーザ
protected function getCurrentUser(){
    return $this->Auth->user();
}

// 承認機構
public function isAuthorized($user) {
    // 管理者は全許可
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }
    // デフォルトは全拒否
    return false;
}

// 毎度実行するもの
function beforeFilter(){
    // 認証
    // 全てのコントローラの index と view アクションでログインを必要としないこととする。
    //$this->Auth->allow();//'index', 'view');

    // ログイン中ユーザ
    $currentUser = $this->getCurrentUser();
    $this->set('currentUser', $currentUser);
}

login.ctp

app/View/Users/login.ctp

<div class="users form">
    <?php echo $this->Session->flash('auth'); ?>
    <?php
    echo $this->Form->create('User',
        array(
            'inputDefaults' => array(
                'div' => 'form-group',
                'label' => array(
                    'class' => 'col col-md-3 col-xs-3 control-label'
                ),
                'wrapInput' => 'col col-md-5 col-xs-5',
                'class' => 'form-control'
            ),
            'class' => 'well form-horizontal'
        )
    );
    ?>
    <fieldset>
        <legend>ユーザ名とパスワードを入力してください</legend>
        <?php
        echo $this->Form->input('username');
        echo $this->Form->input('password');
        ?>
    </fieldset>
    <!-- Submit -->
    <div class="form-group">
        <?php
        echo $this->Form->submit(
            'Login',
            array('div' => 'col col-md-5 col-xs-5 col-md-offset-3 col-xs-offset-3', 'class' => 'btn btn-default')
        );
        ?>
    </div>
    <?php echo $this->Form->end(); ?>
</div>

routes.php

app/Config/routes.php

Router::connect('/', array('controller' => 'dashboard', 'action' => 'index'));

DashboardController

<?php
App::uses('AppController', 'Controller');
class DashboardController extends AppController {
    public function isAuthorized($user) {
        return true;
    }
    public $components = array('Session');
    public $uses = array('Account', 'User');
    public function index() {
    }
}

Dashboard/index.ctp

app/View/Dashboard/index.ctp

<div class="dashboard index">
    <h2>
        ダッシュボード
    </h2>
    <div>
        <?php echo h($currentUser['username']); ?> でログイン中。
    </div>
    <div style="margin-top: 16px;">
        <table class="table" style="width: 300px;">
        <tr><td>ユーザ名</td><td><?php echo h($currentUser['username']); ?></td></tr>
        <tr><td>権限</td><td><?php echo h($currentUser['role']); ?></td></tr>
        </table>
    </div>
</div>

AppShell

app/Console/Command/AppShell.php

// ユーザuser/userを追加
// Usage: ./Console/cake app userDefault
public function userDefault(){
    $params = array();
    $params['username'] = 'uesr';
    $params['password'] = 'user';
    $params['role'] = 'admin';
    $this->User->create();
    $ret = $this->User->save(array('User' => $params));
    var_dump($ret);
}

navbar

<li
    <?php if($this->params["controller"] == 'users' && ($this->params["action"] == 'login' || $this->params["action"] == 'info')){ echo 'class="active"'; } ?>
    >
    <?php if(!$currentUser): ?>
        <a href="/users/login">ログイン</a>
    <?php else: ?>
        <a href="/users/info"><?php echo h($currentUser['username']); ?>でログイン中</a>
    <?php endif; ?>
</li>