- 2010-03-16 (火) 14:18
- PHP
前回の続きです。
今回は第2弾です。元ネタはこちら。
前回の例には2点問題があるので、解決していきましょう。
1点目に、URLをパースする方法
2点目に、コマンドの実行がswitch文での振り分け
目的は、もっとフレキシブルなURLの解釈をさせることです。そのために基本的なコマンドオブジェクトを作成していきます。
<?php
class Axial_Command
{
var $commandName = '';
var $parameters = array();
// コマンド名格納、パラメータ格納
function Axial_Command($commandName,$parameters)
{
$this->commandName = $commandName;
$this->parameters = $parameters;
}
// コマンド名取得
function getCommandName()
{
return $this->commandName;
}
// パラメータ格納
function getParameters()
{
return $this->parameters;
}
}
?>
次にURLをパースするクラスが必要です。前回で紹介したパース処理と上の処理を使ってコマンドオブジェクトを作成します。
<?php
class Axial_UrlInterpreter
{
var $command;
function Axial_UrlInterpreter()
{
$requestURI = explode('/', $_SERVER['REQUEST_URI']);
$scriptName = explode('/',$_SERVER['SCRIPT_NAME']);
for($i= 0;$i < sizeof($scriptName);$i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$commandArray = array_values($requestURI);
$commandName = $commandArray[0];
$parameters = array_slice($commandArray,1);
$this->command = new Axial_Command($commandArray[0],$parameters);
}
function getCommand()
{
return $this->command;
}
}
?>
最後にコマンドオブジェクトを実行箇所に渡します。まだこの時点ではコードをシンプルにさせたいのでswitch文を使用しておきます。
<?php
class Axial_CommandDispatcher
{
var $command;
function Axial_CommandDispatcher($command)
{
$this->command = $command;
}
function Dispatch()
{
switch ($this->command->getCommandName())
{
case 'commandOne' :
include('commandone.php');
break;
case 'commandTwo' :
include('commandtwo.php');
break;
case '':
include('root.php');
break;
default:
include('default.php');
break;
}
}
}
?>
今回の挙げたものを統合した例です。前回に作成した.htaccessが必要です。動作するデモとサンプルソースがこちらからダウンロードできます。
// 今回例に挙げたファイル読み込み
include('axial.command.php');
include('axial.urlinterpreter.php');
include('axial.commanddispatcher.php');
// URLパース処理 コマンド名取得 axial.command.phpにコマンド名とパラメータ格納
$urlInterpreter = new Axial_UrlInterpreter();
// 上のパース処理からコマンド名取得
$command = $urlInterpreter->getCommand();
// 実行処理にコマンド名格納
$commandDispatcher = new Axial_CommandDispatcher($command);
// コマンド実行
$commandDispatcher->Dispatch();
次にチュートリアルでswitch処理を直します。
以上です。
ではでは。
- Newer: フレームワークを作る ルーティング処理 調査編 その3
- Older: フレームワークを作る ルーティング処理 調査編 その1
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://blog.cypher-works.com/wp-trackback.php?p=1132
- Listed below are links to weblogs that reference
- フレームワークを作る ルーティング処理 調査編 その2 from CYPHER-WORKS(コピペプログラマから書けるプログラマへ)