Create a gist now

Instantly share code, notes, and snippets.

@bz0 /.htaccess
Last active Feb 4, 2018

Embed
What would you like to do?
ルーティング
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
<?php
$router = new bz0\Router();
$router->get("/router/test/:id", function(){
echo "test<br>";
});
$router->get("/router/test2/", function(){
echo "test2<br>";
});
<?php
namespace bz0;
class Router{
//メソッド
public $method;
//ディレクトリパス
public $path;
//パス内の引数
public $args;
//URLパラメータ
public $params;
public function __construct(){
$this->method = $_SERVER['REQUEST_METHOD'];
$this->path = $_SERVER['REQUEST_URI'];
}
private function method($method){
return $this->method === strtoupper($method);
}
private function pathMatch($realPath, $path){
$realPathList = explode("/", $realPath);
$pathList = explode("/", $path);
echo $realPath . "<br>";
//階層数が同じ
if ($this->dirCountMatch($realPathList, $pathList)){
foreach($pathList as $i => $dirName){
if (preg_match("/^:(.*)/", $dirName, $match)){
//ディレクトリ名の取得
$this->args[$match[1]] = $realPathList[$i];
}else{
if (!$this->dirNameCheck($realPathList[$i], $dirName)){
return false;
}
}
}
}else{
return false;
}
return true;
}
private function params(){
switch ($this->method) {
case 'GET':
$params = strstr($this->path, '?');
parse_str($params, $this->params);
break;
case 'POST':
foreach (array_keys($_POST) as $key) {
$this->params[$key] = $_POST[$key];
}
break;
case 'PUT':
case 'DELETE':
parse_str(file_get_contents('php://input'), $this->params);
break;
default:
break;
}
}
private function dirCountMatch($realPathList, $pathList){
return count($realPathList) === count($pathList);
}
private function dirNameCheck($realDirName, $dirName){
return $realDirName === $dirName;
}
public function get($path, $callable){
if($this->method('get')){
if ($this->pathMatch($this->path, $path)){
$this->params();
$callable = $callable->bindTo($this);
$callable();
}
}
}
public function post($path, $callable){
if($this->method('post')){
if ($this->pathMatch($this->path, $path)){
$this->params();
$callable = $callable->bindTo($this);
$callable();
}
}
}
public function put($path, $callable){
if($this->method('put')){
if ($this->pathMatch($this->path, $path)){
$this->params();
$callable = $callable->bindTo($this);
$callable();
}
}
}
public function delete($path, $callable){
if($this->method('delete')){
if ($this->pathMatch($this->path, $path)){
$callable = $callable->bindTo($this);
$callable();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment