一个功能完备的url路由:Hcrail

写在前面

功能完备还有待添加,嘿嘿

正文

之前学习了一下composer,正好也缺一个很优雅的 url 路由,于是就来实践一下,这个路由需要php 5.3以上环境支持,因为用到了匿名回调。

代码

<?php
namespace cmhc\Hcrail;

class Hcrail
{

    /**
     * callback function
     * @var callable
     */
    protected static $callback;

    /**
     * match string or match regexp
     * @var string
     */
    protected static $match;

    protected static $routeFound = false;

    /**
     * deal with get,post,head,put,delete,options,head
     * @param   $method
     * @param   $arguments
     * @return
     */
    public static function __callstatic($method, $arguments)
    {
        self::$match = str_replace("//", "/", dirname($_SERVER['PHP_SELF']) . '/' . $arguments[0]);
        self::$callback = $arguments[1];
        self::dispatch();
        return;
    }

    /**
     * processing ordinary route matches
     * @param  string $requestUri
     * @return
     */
    public static function normalMatch($requestUri)
    {
        if (self::$match == $requestUri) {
            self::$routeFound = true;
            call_user_func(self::$callback);
        }
        return;
    }

    /**
     * processing regular route matches
     * @param  string $requestUri
     * @return
     */
    public static function regexpMatch($requestUri)
    {
        //处理正则表达式
        $regexp = self::$match;
        preg_match("#$regexp#", $requestUri, $matches);
        if (!empty($matches)) {
            self::$routeFound = true;
            call_user_func(self::$callback, $matches);
        }
        return;
    }

    /**
     * dispatch route
     * @return
     */
    public static function dispatch()
    {
        if (self::$routeFound) {
            return ;
        }
        $requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $requestMethod = $_SERVER['REQUEST_METHOD'];

        if (strpos(self::$match, '(') === false) {
            self::normalMatch($requestUri);
        } else {
            self::regexpMatch($requestUri);
        }

    }

    /**
     * Determining whether the route is found
     * @return boolean
     */
    public static function isNotFound()
    {
        return !self::$routeFound;
    }

}

介绍以及使用

Hcrail

Hcrail是一个简单的PHP路由,代码不到100行

使用

如果你安装了composer,可以直接用composer吧Hcrail集成到你的项目中去,使用如下代码

require: {
    "cmhc/Hcrail": "dev-master"
}

Hcrail支持普通匹配和正则匹配,如下

普通匹配,匹配首页

use cmhc\Hcrail\Hcrail;

Hcrail::get("/",function(){
    echo 'hello';
});

正则匹配,匹配类似 http://localhost/6666.html 的地址

Hcrail::get("/([0-9]*)\.html",function($args){
    echo $args[1];
});

服务器配置

apache 在根目录建立 .htaccess 文件

RewriteEngine On
RewriteBase /Hcrail

RewriteCond %{REQUEST_FILENAME}% !-f
RewriteCond %{REQUEST_FILENAME}% !-d

RewriteRule ^.*$ index.php [L]

nginx

location / {
    try_files $uri $uri/ /index.php?/$uri;
}

后记

这个我将会在一些项目上来实践,进而发现一些不足,逐渐让这个路由完备起来,但我希望这个路由仍旧越简单越好,保持最基础的功能!

github地址 https://github.com/cmhc/Hcrail

赞赏

微信赞赏支付宝赞赏

作品

发表评论

您的电子邮箱地址不会被公开。