cakephp2.doc_004
最終投稿日:2019年11月20日
MyUserAgentComponent として定義
以下ソース
class MyUserAgentComponent extends Component {
private $ua;
private $device;
public function initialize(Controller $controller) {
$this->controller = $controller;
}
public function set(){
$this->ua = mb_strtolower($_SERVER['HTTP_USER_AGENT']);
if(strpos($this->ua,'iphone') !== false){
$this->device = 'mobile';
}elseif(strpos($this->ua,'ipod') !== false){
$this->device = 'mobile';
}elseif((strpos($this->ua,'android') !== false) && (strpos($this->ua, 'mobile') !== false)){
$this->device = 'mobile';
}elseif((strpos($this->ua,'windows') !== false) && (strpos($this->ua, 'phone') !== false)){
$this->device = 'mobile';
}elseif((strpos($this->ua,'firefox') !== false) && (strpos($this->ua, 'mobile') !== false)){
$this->device = 'mobile';
}elseif(strpos($this->ua,'blackberry') !== false){
$this->device = 'mobile';
}elseif(strpos($this->ua,'ipad') !== false){
$this->device = 'tablet';
}elseif((strpos($this->ua,'windows') !== false)
&& (strpos($this->ua, 'touch') !== false && (strpos($this->ua, 'tablet pc') == false))){
$this->device = 'tablet';
}elseif((strpos($this->ua,'android') !== false) && (strpos($this->ua, 'mobile') === false)){
$this->device = 'tablet';
}elseif((strpos($this->ua,'firefox') !== false) && (strpos($this->ua, 'tablet') !== false)){
$this->device = 'tablet';
}elseif((strpos($this->ua,'kindle') !== false) || (strpos($this->ua, 'silk') !== false)){
$this->device = 'tablet';
}elseif((strpos($this->ua,'playbook') !== false)){
$this->device = 'tablet';
}elseif((strpos($this->ua,'docomo') !== false)){
$this->device = 'Ktai';
}elseif((strpos($this->ua,'kddi') !== false)){
$this->device = 'Ktai';
}elseif((strpos($this->ua,'vodafone') !== false)){
$this->device = 'Ktai';
}elseif((strpos($this->ua,'softbank') !== false)){
$this->device = 'Ktai';
}else{
$this->device = 'others';
}
return $this->device;
}
}
[ Controller 側 ] ※AppController が良いかも。
public $components = array("Session","MyUserAgent");
public function beforeFilter(){
parent::beforeFilter();
$ua = $this->Session->read("ua");
if(!isset($ua)){
$ua = $this->MyUserAgent->set();
//初回以降は session から呼び出せる
$this->Session->write("ua",$ua);
}
}