搭建REST风格的服务器

今天购入阿里云,然后准备在阿里云上搭建rest风格的API,首先就是URL规则重写

1、URL重写

在apache服务器下,修改httpd.conf文件

(1)Options FollowSymLinks

AllowOverride None

改为

Options FollowSymLinks

AllowOverride All

(2)去掉下面的注释

LoadModule rewrite_module modules/mod_rewrite.so

2、根目录下添加.htaccess文件,完成重写规则

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]


3、实现index.php

首先是define相关的文件夹路径,比如:

//根路径

define('ROOT_PATH',dirname(__FILE__));

define('CONF_PATH',ROOT_PATH.'/conf/');

然后调用dispatch做分发处理

4、实现dispatch.php

通过获取请求参数来分发到不同的文件和方法中

public function dealUrl(){

$url =strip_tags( $_SERVER['REQUEST_URI'] );

$pathseg =explode('/',trim($url,'/'));

$method = Http_Request::get('method');

if(is_null($method)){

throw new Exception('not_found');

}

$resseg =explode('?',trim($pathseg[1],'?'));

$args[] = $resseg[0];

$strFileName =CONTROLLER_PATH.$resseg[0]."Controller.php";

$this->_controllerFile=$resseg[0]."Controller.php";

$this->_strControllerName= $resseg[0];

if(is_file($strFileName)) {

include_once'Controller.php';

include_once$strFileName;

if(!class_exists($this->_strControllerName)) {

throw newException('not_found');

return'false';

}

$objController =new$this->_strControllerName();

if(!method_exists($objController,$method)){

throw newException('not_found');

}

$objController->$method();

}

}

大工告成!

你可能感兴趣的:(搭建REST风格的服务器)