getParam()でRequestを取る際のデフォルト値

Zend FrameworkのコントローラでRequest値を受け取る処理をするのに、getParam()或いはgetParams()を使用して受け取るのが一般的だと思います。
getParamで受け取る時は値が無い場合の初期値を組み込むことが出来るので、是非活用しましょう。

[php]
/* $_REQUEST['page']に値がセットされていない場合、
文字列「index.html」が返される。
 #2番目の引数がそのまま返されるので文字列とは限りません。*/
$page = $this->getRequest()->getParam(‘page’, “index.html”);
[/php]

ソースを見ればすぐわかるのですが、
[php]
abstract class Zend_Controller_Request_Abstract…
public function getParam($key, $default = null)
{
$key = (string) $key;
if (isset($this->_params[$key])) {
return $this->_params[$key];
}
return $default;
}
[/php]
こういう仕組みになっているのに気づかずに、ただ値が入っていない場合はnullを返す、と思っており、

[php]
$page = $this->getRequest()->getParam(‘page’);
$page = !is_null($page) ? $page : “index.html”;
[/php]

という処理にしてました。ということでメモ。

関連する記事:

Powered by

  1. Ambien online viagra. - trackback on 2010/10/8 金曜日 at 20:27:10

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Trackbacks and Pingbacks: