- Posted at 2008/12/22 1:36
- Categories: CakePHPで楽天API
今回は、検索フォームで商品を絞り込めるようにしてみた。
なお、この連載の過去の記事一覧は「CakePHPで楽天API」を見ていただきたい。
まず、「app/config/routes.php」に以下を追加する。
app/config/routes.php
Router::connect('/searches/*', array('controller' => 'Searches', 'action' => 'index'));
モデルは次のようになる。前回とちょっと変えたのは、APIのパラメータをメソッドに書いていたのをやめて、クラスで定義してみた。
app/models/Item.php
class Item extends AppModel {
var $name = "Item";
var $api_def = array(
'developerId' => DEV_ID,
'affiliateId' => AFF_ID,
'operation' => 'ItemSearch',
'version' => '2008-09-01',
);
function findAll($conditions = array()) {
$req = 'http://api.rakuten.co.jp/rws/1.12/rest?';
$api_params = array_merge($conditions,$this->api_def);
uses('Xml');
$req .= http_build_query($api_params);
$xml = new XML($req);
$xml_array = Set::reverse($xml);
return $xml_array['Response']['Body']['ItemSearch'];
}
}
次にコントローラは以下のようになる。
app/controllers/Searches_controller.php
class SearchesController extends AppController {
var $name = 'Searches';
var $uses = 'Item';
var $helpers = array ('Html','Form');
function index($term=null,$page=1){
if ($term === null){
$term = $this->params['data']['term'];
}
$this->set('term',$term);
//リクエスト用パラメータ
$conditions = array (
'keyword' => MAINKWD." ".$term,
'hits' => PERPAGE,
'page' => $page,
);
//モデルからデータ取得
$data = $this->Item->findAll($conditions);
//商品配列
$this->set('items', $data['Items']['Item']);
//所得アイテム総数
$this->set('count', $data['count']);
//ページング処理
require_once ('Pager.php');
//Pager用パラメータ
$p_options = array (
"totalItems" => $data['count'],
"perPage" => PERPAGE,
'urlVar' => 'page',
'path' => FULL_BASE_URL . '/tokoton/searches',
'fileName' => urlencode($term).'/%d',
'append' => false,
'currentPage' => $page,
);
$pager = & Pager :: factory($p_options);
$navi = $pager->getLinks();
$this->set('navi', $navi["all"]);
}
}
今回は、URLとして、「/tokoton/(検索語)/(ページ)」という表現にしたかったので、上記のようになっている。
で、肝心のビューには以下の入れる。
<form action="/tokoton/searches" method="post">
< ?php
echo $form->text("term");
echo $form->submit("検索");
?>
</form>
検索フォームからは、POSTデータとしてパラメータを渡しているが、ページめくりの際は、GET情報でパラメータを渡すようになっている。
う〜ん、もっとシンプルなやり方はないかな〜〜・・・(^^;)
こちらの記事もあわせてどうぞ!
関連書籍
- Newer: JPの年賀状コンシェルジュ
- Older: メルダス (もしもドロップシッピング)
Comments:0
Trackbacks:1
- Trackback URL for this entry
- http://www.multiburst.net/ElectricBrain/2008/12/cakephpweb_4/trackback
- Listed below are links to weblogs that reference
- CakePHPで楽天WEBサービスを使う(検索フォーム) from ElectricBrain Standard
- pingback from ElectronicBrain is eating BreakFast - CakePHPで楽天WEBサービスを使う(ソート順) 09-01-07 (水) 17:34
-
[...] 前回は、検索フォームで商品を検索できるようにしました。 [...]

















































