Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active August 14, 2018 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/5513049835a1bad4830c90431a1171b2 to your computer and use it in GitHub Desktop.
Save yano3nora/5513049835a1bad4830c90431a1171b2 to your computer and use it in GitHub Desktop.
[cakephp: Controller] Controller class on CakePHP3. #php #cakephp

OVERVIEW

リクエストとレスポンスオブジェクト - book.cakephp.org

コントローラはリクエストオブジェクト ( Cake\Http\ServerRequest ) とレスポンスオブジェクト ( Cake\Http\Response ) の参照 & 操作に終始する。

  1. リクエストを取得 & 操作
  2. モデルに問い合わせ
  3. ビューのセットアップ
  4. レスポンス返却

リクエスト

// get - /books/edit/1 や method=getのフォームなど
public function edit($id=null, $foo=null){
    $var = $this->request->param('foo');
}

// querystring - /book?hoge=2&fuga=3 など
$q = $this->request->query();
var_dump($q);

// post
$this->request->data('User.name');
$this->request->data('password', $this->request->data('new_password'));  // セットもできるよ

リクエストのメソッド is ?

if ($this->request->is('post')) {
    $this->Flash->success('posted values!');
    var_dump($this->request->data('input_name'));
}

バリデーションエラー確認

public function add() {
  $event = $this->Events->newEntity();
  if ($this->request->is('post')) {
    $event = $this->Events->patchEntity($event, $this->request->getData());
    if ($this->Events->save($event)) {
      $this->Flash->success(MSG_CREATE_SUCCESS);
      return $this->redirect(['action' => 'index']);
    }
    die(debug($event->errors()));  // エンティティのerrors()に入っている
    $this->Flash->error(MSG_CREATE_ERROR);
  }
  $this->set(compact('event'));
  $this->set('_serialize', ['event']);
}

レンダリングTemplateを変えたい

// 初期処理メソッド( initialize , beforeFilter等 )で...
$this->viewBuilder()->layout("admin");

アクションを内部で切り替え

$this->setAction('action_name',$arg);
(引数は省略OK、後のコードも全て実行して移動する仕様)

コントローラからビューへ値渡し

$foo = 1;
$bar = 'aaa';
$this->set(compact('foo', 'bar');
// ↑各ビューで$foo,$barが使える
// $this->set('foo', $foo);でもOK

別コントローラやビューの値を参照

$this->viewVars['custcode'];

コンポーネントの読み込み

// in AppController
public function initialize()
{
  parent::initialize();
  $this->loadComponent('Auth');
  $this->loadComponent('Security');
  $this->loadComponent('Csrf');
}

リダイレクト

// return 仕様になってます
if ($this->Users->save($user)) { //DB保存できたら
    $this->Flash->success(__('saved');
    return $this->redirect(['action'=>'index']);
}

// 引数 ( /users/edit/1 )
return $this->redirect([
  'controller' => 'Users',
  'action'=>'edit',
   $id,
]);

// QueryString
return $this->redirect([
  'action' => 'index',
  '?' => ['sort' => 'created'],
]);

// Hash
return $this->redirect([
  'action' => 'view',
  '#' => 'user-profile',
]);

フラッシュ

$this->Flash->success(__('Success.'));
$this->Flash->error(__('Failed.'));

Session/セッション

// Prepare in AppController
public function initialize() {
  parent::initialize();
  $this->Session = $this->request->session();  // アクセスのらくちん化
}

// Read
$hoge = $this->Session->read('Hoge.hoge');

// Read with Delete
echo $this->Session->consume('User.token');

// Write
$this->Session->write('Hoge.hoge', 'hoge');
$this->Session->write([
  'Member.name' => 'taro',
  'Member.mail' => 'taro@test.com',
]);

// Check ( Return bool )
if ($this->Session->check('User.loggedIn')) { /* ... */ }

// Delete
$this->Session->delete('Hoge');
$this->Session->delete('User.password');

// Destroy ( Delete all )
$this->Session->destroy();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment