【PHP】自動振り分けクラスを書いてみる
既に運用しているサイトに、ユーザエージェントでPC版とSP版に自動振り分けする機能を追加して欲しいという依頼がありましたので作ってみました。
PHPの書き方がだいぶ怪しいので誰かに見てもらえれば...!思い買いてみます。
仕様は以下のとおり。
仕様
- .htaccess使用不可
- 言語はPHP
- スマホ版のディレクトリは /sp/
- /hoge/ にアクセスした時、端末がスマホであれば /sp/hoge/ にリダイレクトする
- PC版にしかページがない場合、任意のページにリダイレクトさせる
- URLに ?mode=pc というクエリが付いていた時はリダイレクトさせない
コード
上記の仕様を元に作成したのがこのコードです。
<?php class SpRedirect { var $spdir = '/sp'; var $showPCSiteQuery = '?mode=pc'; var $ua; var $spPath; var $extendRedirectPath; var $currentPath; var $isSmartPhone = false; var $isShowPCSite = false; function SpRedirect($exRedirectPath, $spdir = null, $showPCSiteQuery = null) { if(!is_null($spdir)) { $this -> spdir = $spdir; } if(!is_null($showPCSiteQuery)) { $this -> showPCSiteQuery = $showPCSiteQuery; } $this -> currentPath = $_SERVER['REQUEST_URI']; $this -> ua = $_SERVER['HTTP_USER_AGENT']; $this -> spPath = $this -> spdir . $this -> currentPath; if(is_array($exRedirectPath)) { $this -> extendRedirectPath = $exRedirectPath; } // PCページを表示するのかを判定 if(strpos($this -> currentPath, $this -> showPCSiteQuery) !== false) { $this -> isShowPCSite = true; } } function isSmartPhone() { if((strpos($this -> ua, 'iPhone') !== false) || (strpos($this -> ua, 'iPod') !== false) ||(strpos($this -> ua, 'Android') !== false)) { $this -> isSmartPhone = true; } else { $this -> isSmartPhone = false; } } /** * スマホ版ページのURLを生成 */ function generateSpPath() { foreach($this -> extendRedirectPath as $extendRedirectPathKey => $extendRedirectPathVal) { if(strpos($this -> spPath, $extendRedirectPathKey) === false) { continue; } $this -> spPath = str_replace($extendRedirectPathKey, $extendRedirectPathVal, $this -> spPath); } } /** * リダイレクト */ function redirectSpPage() { if($this -> isSmartPhone && !$this -> isShowPCSite) { $this -> generateSpPath(); header('Location: ' . $this -> spPath); } } }
使い方
SpRedirectクラスをインスタンス化して使用します。
<?php $redirect = new SpRedirect(); $redirect -> redirectSpPage();
仕様5.のように任意のページにリダイレクトさせたい場合は、そのリストを引数に指定してあげます。
<php $extendRedirectPath = array( 'hoge' => '/fuga' ); $redirect = new SpRedirect($extendRedirectPath); $redirect -> redirectSpPage();
初めてPHPのクラスを書いたのですが、はたしてクラスにする必要があったのかどうか...。
まともにPHPを書いたことがないので、もっとスマートな書き方がある等ありましたら教えて欲しいです。。