UNIX的なアレ

UNIX的なこととかいろいろ

CakePHPからJSONをつかうモデルをつくった

JSONシリアライズされているAPIをたたくようなモデルを作ってみました。ローカルに配置しているJSONのファイルにも対応しています。
キャッシュをさせるような仕組みになっているので、多数叩くような場合にも効果的です。
modelの下に、json.phpというファイル名で保存してください。

<?php
class Json extends AppModel {
  var $name = 'Json';
  var $useTable = false ;

  /*
   * jsonデータの取得
   * @param string JSONファイルへのパス
   * @param boolean キャシュさせるか
   * @return mixed
   */
  function find( $path , $cache = false ){
    if ( !substr_count( $path , 'http://' ) && !file_exists( $path ) ){
      return false ;
    }

    if ( $cache ){
      $cache_key = md5( $path );

      if (($data=Cache::read($cache_key))!==false){
	return $data ;
      }

      $data = call_user_func_array(array($this,__FUNCTION__),array($path,false));
      Cache::write( $cache_key , $data );
    }

    $data = json_decode(file_get_contents($path),true);
    return $data ;
  }

  /*
   * jsonのキャッシュをクリア
   * @param string jsonファイルへのパス
   * @return boolean
   */
  function cache_clear( $path = null ){
   return Cache::delete( md5($path) );
  }

}

使いたいときは簡単です。以下のようにコントローラーから呼び出せばOKです。とりあえずTwitterAPIでサンプルを。

<?php
class AppController extends Controller {
  var $uses = array('Json');
  
  function get(){
    $data = $this->Json->find('http://api.twitter.com/1/statuses/public_timeline.json');
    debug( $data );
  }
}

これでJSONの取り扱いがより楽になりますねー!