2013年5月5日日曜日

AngularJSのチュートリアルをCakePHPでやってみる。その3

Step5 XMLHttpRequestと依存性の注入

3日目のソースが欲しい方はこちらです。
サンプルページはこちらです。

jsonを表示する設定

routes.phpに以下を追加

Router::parseExtensions('json');

CakePHPのコントローラ作成

CakePHPのコントローラ、JsonController.phpを追加します。 これでjsonが表示されます。CakePHPのビューはありません。また、データは本来はDBにテーブル作ってinsertすべきでしょうけど、手間なので直接配列を書いてます。

<?php
App::uses('AppController', 'Controller');

/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package     app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class JsonController extends AppController {

/**
 * Controller name
 *
 * @var string
 */
    public $name = 'Json';

/**
 * This controller does not use a model
 *
 * @var array
 */
    public $uses = array();

/**
 * レイアウトを決める
 */
    public $layout = "common";
 /**
  * コンポーネントの設定
  */
    public $components = array('Tools.ApiTool','RequestHandler');

/**
 * ヘルパーを設定する。
 */
    public $helpers = array();
/**
 * Displays a view
 *
 * @param mixed What page to display
 * @return void
 */
    public function index() {}

    public function api_get($type = null){
    // リクエストをデバッグログに書き出し
    $this->ApiTool->logingRequest($this->request);
    // 引数チェック。空か、指定タイプ以外だったら404エラー
    $this->ApiTool->checkType($type,array('phones'));
    // タイプごとにphonesを作り分ける。
    if ($type == 'phones'){
     $phones = $this->__getPhones();
     $this->set('phones',$phones);
    }
    // ビュークラスをJSONにする
    $this->viewClass = 'Json';
    $this->set('_serialize', array('phones'));
 }

    public function beforeFilter() {
        parent :: beforeFilter();
    }

    //スマートフォンのデータ。配列で返す。
    public function __getPhones(){
        $phones = array(
                array(
                    "age"=> 0, 
                    "id"=> "motorola-xoom-with-wi-fi", 
                    "imageUrl"=> "img/phones/motorola-xoom-with-wi-fi.0.jpg", 
                    "name"=> "Motorola XOOM\u2122 with Wi-Fi", 
                    "snippet"=> "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
                ), 
                array(
                    "age"=> 1, 
                    "id"=> "motorola-xoom", 
                    "imageUrl"=> "img/phones/motorola-xoom.0.jpg", 
                    "name"=> "MOTOROLA XOOM\u2122", 
                    "snippet"=> "The Next, Next Generation\n\nExperience the future with MOTOROLA XOOM, the world's first tablet powered by Android 3.0 (Honeycomb)."
                ), 
                array(
                    "age"=> 2, 
                    "carrier"=> "AT&amp;T", 
                    "id"=> "motorola-atrix-4g", 
                    "imageUrl"=> "img/phones/motorola-atrix-4g.0.jpg", 
                    "name"=> "MOTOROLA ATRIX\u2122 4G", 
                    "snippet"=> "MOTOROLA ATRIX 4G the world's most powerful smartphone."
                ), 
                array(
                    "age"=> 3, 
                    "id"=> "dell-streak-7", 
                    "imageUrl"=> "img/phones/dell-streak-7.0.jpg", 
                    "name"=> "Dell Streak 7", 
                    "snippet"=> "Introducing Dell\u2122 Streak 7. Share photos, videos and movies together. It\u2019s small enough to carry around, big enough to gather around."
                ), 
                array(
                    "age"=> 4, 
                    "carrier"=> "Cellular South", 
                    "id"=> "samsung-gem", 
                    "imageUrl"=> "img/phones/samsung-gem.0.jpg", 
                    "name"=> "Samsung Gem\u2122", 
                    "snippet"=> "The Samsung Gem\u2122 brings you everything that you would expect and more from a touch display smart phone \u2013 more apps, more features and a more affordable price."
                ), 
                array(
                    "age"=> 5, 
                    "carrier"=> "Dell", 
                    "id"=> "dell-venue", 
                    "imageUrl"=> "img/phones/dell-venue.0.jpg", 
                    "name"=> "Dell Venue", 
                    "snippet"=> "The Dell Venue; Your Personal Express Lane to Everything"
                ), 
                //...
                //中略
                //...
                array(
                    "age"=> 19, 
                    "id"=> "motorola-charm-with-motoblur", 
                    "imageUrl"=> "img/phones/motorola-charm-with-motoblur.0.jpg", 
                    "name"=> "Motorola CHARM\u2122 with MOTOBLUR\u2122", 
                    "snippet"=> "Motorola CHARM fits easily in your pocket or palm.  Includes MOTOBLUR service."
                )
        );
        return $phones;
    }
}
?>

で、「/angularjs_tutorial/json/api_get/phones.json」にアクセスすると以下の様な画面でJSONが吐出されているのが確認出来ます。

AngularJSのコントローラを作成。

controllers.jsを修正。上で作ったJSONのデータを「$http.get()」メソッドで取得しています。公式のチュートリアルのコードは成功した時の処理しか無いですが、 動作がわかりにくいので失敗した時の処理も追加してます。
ここで追加されている「$http」はサービスというものらしいです。コントローラの引数に必要なサービスをその都度指定して利用するようです。
このへんがAngularJSの依存性の注入に当たる様な、そうで無いような…。どなたかわかる方教えて下さい。

function PhoneListCtrl($scope,$http) {
    $http.get('../json/api_get/phones.json').success(function(data,status) {
        console.log('success');
        console.log(data);
        console.log(status);
        $scope.phones = data.phones;
        //$scope.phones = data.phones.splice(0,5);  //実験用
    }).error(function(data, status) {
            console.log('error');
            console.log(data);
            console.log(status);
    });
}

view側に変更はありません。でサンプルページのように動作しているのが確認出来ます。
今日はこんな所で終わりです。ではでは。

環境とか

項目内容
PHPフレームワークCakephp 2.2.5
CSSフレームワークTwitter bootstrap 2.2.2
JSフレームワークAngularJS 1.0.5
IDESublimeText 2
開発環境?MAMP
PCiMac
OSMac OS Lion

0 件のコメント:

コメントを投稿