<?php
class
Dispatcher{
public
static
function
start(){
if
(
$_GET
['
pathinfo
'] && C('Epoch.ROUTE_ON') == true){
self::ParseRoute();
}
$Control
=
$_GET
[C('Epoch.VAR_CONTROLLER')];
$Action
=
$_GET
[C('Epoch.VAR_ACTION')];
$Control
=
empty
(
$Control
) ? C('Epoch.DEFAULT_CONTROLLER') :
$Control
;
$Action
=
empty
(
$Action
) ? C('Epoch.DEFAULT_ACTION') :
$Action
;
$ControlPath
= APP_PATH .'Controller/'.
$Control
. C('Epoch.DEFAULT_CONTROLLER_SUFFIX');
if
(
file_exists
(
$ControlPath
)){
require_once
$ControlPath
;
$Controlor
=
$Control
.'Controller';
if
(
class_exists
(
$Controlor
)){
$obj
=
new
$Controlor
();
if
(method_exists(
$obj
,
$Action
)){
$obj
->
$Action
();
}
else
{
self::Show('控制器动作不存在!');
}
}
else
{
self::Show('控制器无法加载!');
}
}
else
{
self::Show('控制器['.
$ControlPath
.']不存在!');
}
}
public
static
function
Route(
$Controller
,
$Action
,
$Param
){
$routes
= C('Epoch.ROUTE');
if
(
is_array
(
$routes
)){
foreach
(
$routes
as
$pattern
=>
$route
){
$uri
= false;
if
(
empty
(
$route
[0]) ||
empty
(
$route
[1])){
continue
;
}
preg_match_all('/[\d+]/',
$pattern
,
$match
);
if
(
count
(
$match
[0]) !=
count
(
$route
[2])){
continue
;
}
if
(
$route
[0] ==
$Controller
&&
$route
[1] ==
$Action
){
$parse
= parse_url_param(
$Param
);
$flag
= 1;
foreach
(
$route
[2]
as
$key
=>
$param
){
if
(! isset(
$parse
[
$param
])){
$flag
= 0;
$uri
= false;
break
;
}
$uri
=
str_replace
('['.
$key
.']',
$parse
[
$param
],
$pattern
);
unset(
$parse
[
$param
]);
}
if
(
$flag
== 0){
continue
;
}
if
(!
empty
(
$parse
)) {
$extParam
= '?';
foreach
(
$parse
as
$key
=>
$value
){
$extParam
.=
$key
.'='.
$value
.'&';
}
$extParam
=
substr
(
$extParam
, 0, -1);
}
$uri
.=
$extParam
;
if
(
$uri
!== false){
return
$uri
;
}
}
}
}
return
false;
}
protected
static
function
ParseRoute(){
$routes
= C('Epoch.ROUTE');
$pathinfo
=
$_GET
['
pathinfo
'];
if
(!
is_array
(
$routes
)){
return
;
}
foreach
(
$routes
as
$pattern
=>
$route
){
for
(
$i
= 0;
$i
< 10;
$i
++){
$res
= isset(
$route
[3][
$i
]) ?
$route
[3][
$i
] : '[A-Za-z0-9]';
$pattern
=
str_replace
('['.
$i
.']', '('.
$res
.'+)',
$pattern
);
}
$pattern
= '/^'.
$pattern
.'$/';
if
(preg_match(
$pattern
,
$pathinfo
,
$match
)){
unset(
$match
[0]);
$_GET
[C('Epoch.VAR_CONTROLLER')] =
$route
[0];
$_GET
[C('Epoch.VAR_ACTION')] =
$route
[1];
foreach
(
$match
as
$key
=>
$value
){
$_GET
[
$route
[2][
$key
- 1]] =
$value
;
}
}
}
}
public
static
function
Show(
$msg
){
EpochException::Show(
$msg
);
}
}