Skip to content

Instantly share code, notes, and snippets.

@kanonji
Last active October 13, 2015 00:18
Show Gist options
  • Save kanonji/4110077 to your computer and use it in GitHub Desktop.
Save kanonji/4110077 to your computer and use it in GitHub Desktop.
CakePHP2のコントローラーが扱う、ブラウザからのパラメーターの取り出し方と、1系との比較。

POST data

$this->request->data['Model']['field'];
$this->request->data('Model.field');    //キーが無い場合はnull

1系では

$this->data;

Query string

$this->request->query['page'];
Hash::get($this->request->query ,'page'); //キーが無い場合はnull

1系では

$this->params['url'];

Passed arguments

$this->request->pass;
$this->request['pass'];
$this->request->params['pass'];

1系では

$this->params['pass'];
$this->passedArgs;

Named parameters

$this->request->named;
$this->request['named'];
$this->request->params['named'];

1系では

$this->params['named'];
$this->passedArgs;

アクションの引数

class CategoriesController extends AppController {
    function view($id, $other){}
}

CakePHP標準のroute設定での例

Router::connect('/:controller/:action/*');

*無しだとアクションは引数を取れません。*が有ると複数の引数を取れます。

$id = '5';
$other = 'foo';

例えば example.com/categories/view/5/foo にアクセスがあると、上記の様な値が入ります。

独自のroute設定での例

Router::connect('/cat/*', array('controller' => 'categories', 'action' => 'view'));
$id = '5';
$other = 'foo';

example.com/cat/5/foo にアクセスがあると、上記の様な値が入ります。

Router::connect('/cat/:foo/:bar', array('controller' => 'categories', 'action' => 'view'), array('pass' => array('foo', 'bar'), 'foo' => '[0-9]+', 'bar' => '[a-z]{1,5}'));

アクションの引数に値を渡すにはRouter::connect()*が必要ですが、このように設定する事も出来ます。この書き方だと、正規表現でのチェックが出来ます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment