php怎样不使用框架的情况下本地模拟url路由,实现localhost/a/id/1这种的访问方式 100
1个回答
展开全部
要实现路由的话你依然需要框架中路由器的支持,因为服务器不能理解你路径的具体含义.所以你需要一个路由器来帮助服务器去处理特定的信息.
不想用现成的就自己写一个简单的,如下:
首先你需要在htdoc下放一个.htaccess来实现单文件入口:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^$ index.php?_url= [QSA,PT,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?_url=$1 [QSA,L]
</IfModule>
然后自己写路由咯, index.php
<?php
//这里添加你想要的路径
$route = array(
//(:num)表示匹配任何数字,(:any)表示任意字符
'a/id/(:num)' => 'TestController:idAction',
'a/any/(:any)' => 'TestController:anyAction',
'a/no' => 'TestController:noAction',
//这里是默认控制器,就是当你访问localhost的时候用
'_DEFAULT_' => 'IndexController:indexAction',
);
//简单的Router
class Router
{
private $route;
public function __construct(array $route)
{
$this->route = $route;
}
public function parse($url)
{
if(empty($url)) {
list($controller, $action) = explode(':', $this->route['_DEFAULT_']);
return array(
'controller' => $controller,
'action' => $action,
'params' => array(),
);
}
$trans = array(
':any' => '[^/]+',
':num' => '[0-9]+'
);
foreach($this->route as $u => $d) {
$pattern = '#^' . strtr($u, $trans) . '$#';
if(preg_match($pattern, $url, $params)) {
list($controller, $action) = explode(':', $d);
array_shift($params);
return array(
'controller' => $controller,
'action' => $action,
'params' => $params,
);
}
}
header("HTTP/1.0 404 Not Found");
exit('Page not found');
}
}
$r = new Router($route);
$arr = $r->parse($_GET['_url']);
require($arr['controller'] . '.php');
//执行控制器的功能
$dispatcher = new $arr['controller'];
call_user_func_array(array($dispatcher, $arr['action']), $arr['params']);
?>
控制器1. Testcontroller.php
<?php
class TestController
{
public function idAction($id)
{
echo "Your int-only id is: {$id}";
}
public function anyAction($any_id)
{
echo "You any id is: {$any_id}";
}
public function noAction()
{
echo "This method take no parameter";
}
}
默认控制器: IndexController.php
<?php
class IndexController
{
public function indexAction()
{
echo "Hello World!";
}
}
把.htaccess, index.php, TestController.php, IndexController.php放在htdoc里就可以了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询