コントローラはリクエストオブジェクト ( Cake\Http\ServerRequest
) とレスポンスオブジェクト ( Cake\Http\Response
) の参照 & 操作に終始する。
- リクエストを取得 & 操作
- モデルに問い合わせ
- ビューのセットアップ
- レスポンス返却
// 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')); // セットもできるよ
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']);
}
// 初期処理メソッド( 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.'));
// 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();