A php micro-route controller

Source: Internet
Author: User
A php micro-route controller and a PHP micro-route controller

Previously, dispatch was used, but the API changes from 4.0 to the current 8.0, especially in the last two major version upgrades. in order to keep the code concise, the backward compatibility feature is lost.
I feel that the author's core idea is not very firm. Therefore, the impulse to build the wheel was born.

Router. lua

This is a micro-routing controller that can run in openresty. it once helped the author make a major revision and is still the second contributor to this project.
The idea is worth learning:

  • The tree structure is used to save the ing between the url and handler. (Searching by tree structure ensures the efficiency of searching callback functions Olog (n ),
    In contrast, the traditional handler method for key ing using regular expressions does not have a stable time to query the callback function. in the worst case, all regular expressions need to be executed once)

  • The reqest method is defined as an encapsulation form of the match function. It is easy to provide a convenient way to map routes.

  • Router

    In view of the above two very good features, we have rewritten this lua library under PHP. Some new features are added to the write process:

  • The error API is added. one API provides two call methods (this method draws on some features in dispatch, a bit like some jquery methods ), it can define both error handler and trigger error handler.

  • Hook APIs are added in two ways.

  • The "before" and "after" hooks are triggered by default. Before and after the actual handler is executed.

  • After the "before" hook, execute the user-defined hook. these hooks are used to specify the list of hooks to be called by the current url when the callback function is defined. (Of course, all these hooks must be user-defined callback functions)

  • Install

    This micro-route controller has been submitted to the packagist website and can be installed using the composer tool.

    composer require lloydzhou/router
    Here is an example in README:
    (New Router ()/* defines the error handling function */-> error (401, function ($ message) {header ('Location:/login', true, 302 ); die ($ message) ;})-> error (405, function ($ message) {header ('Location:/hello/world', true, 302 );}) -> error (406, function ($ message) {die ($ message) ;})/* defines the hook function, except for the built-in before and after called by default, also defines the login check auth */-> hook ('auth', function ($ params) {if ('loyd '= $ params ['name']) return $ params; $ params ['router ']-> error (401, 'forbiden ');})/* defines the after hook function, which supports output in json or jsonp format */-> hook ('after', function ($ result, $ router) {if ($ result) {header ('content-type: application /'. ($ _ GET ['jsoncallback']? 'Javascript ': 'json'); if ($ _ GET ['jsoncallback']) print $ _ GET ['jsoncallback']. '('. json_encode ($ result ). ')'; else print json_encode ($ result) ;}})-> hook ('before', function ($ params) {// $ params ['name'] = 'loydzhou'; return $ params;})/* define url ing */-> get ('/', function () {echo "Hello world !!! ";})-> Get ('/hello/: name', function ($ name) {echo" Hello $ name !!! ";})-> Get ('/hello/: name/again', function ($ name) {echo" Hello $ name again !!! ";}, 'Auth')-> get ('/hello/: name.: ext ', function ($ name, $ ext) {if ('js' = $ ext | 'json' = $ ext) return array ('name' => $ name); return array ('code' => 1, 'MSG '=> 'Error message... ') ;}, 'auth')/* program entry, query the corresponding processing function with the current url, and obtain the variable to execute this function */-> execute ();
    Start the service
    php -S 0.0.0.0:8888 test.php
    Test
    Curl-vvv 127.0.0.1: 8888/hello/url ING failed. The 405 error processing function is triggered and the system automatically redirects to the URL: "/hello/world" curl-vvv 127.0.0.1: 8888/hello/Loyd, "Hello Loyd!" is returned !!! "Curl-vvv 127.0.0.1: 8888/hello/rawyd/again return" Hello lloyd again !!! "Curl-vvv 127.0.0.1: 8888/hello/world/again trigger the 401 error processing function when the hook function auth fails to be processed. The system automatically jumps to the URL:"/login "curl-vvv 127.0.0.1: 8888/hello/lloyd. json supports "/" and ". "is used as the pathinfo separator and works with the after Hook function to return the json format text {" name ":" lloyd "} curl-vvv 127.0.0.1: 8888/hello/lloyd. js? Jsoncallback = test returns the jsonp format text test ({"name": "lloyd"}) curl-vvv 127.0.0.1: 8888/hello/lloyd. jsx? The last suffix of jsoncallback = test does not match. the message test ({"code": 1, "msg": "error message..."}) in jsonp format is output ..."})
    Performance

    The tree structure is used to save the ing between the url and handler. When searching for URL ing functions, the efficiency of the query callback function O (log n) is ensured ).
    In contrast, the traditional handler method for key ing using a regular expression does not have a stable time to query the callback function. in the worst case, all the regular expressions need to be executed once.

    DEMO

    To improve the database while testing. Therefore, this library is used in combination with another ActiveRecord and MicroTpl to write a simple blog, which basically covers the APIs of these libraries.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.