btoさんが作られたSymfony用のプラグインsfMobileIPPluginをCakePHPに移植しました。
- IPアドレスから携帯のキャリアを高速に判定するsymfonyプラグインを作った [blog.bz2.jp]
- sfMobileIPPlugin [openpear.org]
以前から移植したものを利用していたのですが、今開発中の案件でPluginとして抜き出しやすいように書き直したので公開します。
使い方
<?php class HogeController extends AppController { var $components = array('mobileip.MobileIp') ; function index() { pr($this->MobileIp->carrier()) ; } }
READMEにも少し書きましたが、IPアドレスの取得を独自のModelで置き換えられるようにしてあるので、
以下のようなモデルを書けばIPアドレスをDBで管理できます。
<?php App::import('Model', 'mobileip.MobileIp') ; class Ipaddress extends MobileIp { var $name = 'Ipaddress'; var $useTable = 'ipaddresses' ; function afterSave($created) { $last_update_cache = $this->getCacheDir() . DS . 'lastupdated'; @touch($last_update_cache) ; } function find($conditions = null, $fields = array(), $order = null, $recursive = null) { if ( $conditions != 'range' ) return parent::find($conditions, $fields, $order, $recursive) ; $cacheDir = $this->getCacheDir(); $folder = new Folder($cacheDir); $folder->create($cacheDir, 0777); $last_update_cache = $this->getCacheDir() . DS . 'lastupdated'; $cacheFile = $this->getCacheFile(); if (file_exists($cacheFile) && ($this->_getLastModified($last_update_cache) <= filemtime($cacheFile))) { return include($cacheFile); } $ipaddresses = $this->find('all') ; if ( !is_array($ipaddresses) ) return false ; $mobile_ips = array() ; foreach( $ipaddresses as $ip ) { $mobile_ips[$ip['Ipaddress']['type']][] = long2ip($ip['Ipaddress']['ip']) . "/{$ip['Ipaddress']['mask']}" ; } $data = $this->_get_ranges($mobile_ips) ; $file = new File($cacheFile, true); $file->write($data); $file->close(); return include($cacheFile); } }
このModelを使うにはこんな感じ。
<?php class HogeController extends AppController { var $components = array( 'mobileip.MobileIp' => array( 'ModelName' => 'Ipaddress' ) ) ; function index() { pr($this->MobileIp->carrier()) ; } }
CakePHPで携帯サイトを構築されている方は、ぜひ使ってみてください!