• Stars
    star
    1,272
  • Rank 36,997 (Top 0.8 %)
  • Language
    C
  • License
    MIT License
  • Created almost 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pux is a fast PHP Router and includes out-of-box controller tools

Pux

Pux is a faster PHP router, it also includes out-of-box controller helpers.

Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads Daily Downloads

2.0.x Branch Build Status (This branch is under development)

Benchmark

FEATURES

  • Low memory footprint (only 6KB with simple routes and extension installed) .
  • Low overhead.
  • PCRE pattern path support. (Sinatra-style syntax)
  • Controller auto-mounting - you mount a controller automatically without specifying paths for each action.
  • Controller annotation support - you may override the default path from controller through the annotations.
  • Route with optional pattern.
  • Request constraints
    • Request method condition support.
    • Domain condition support.
    • HTTPS condition support.

REQUIREMENT

  • PHP 5.4+

INSTALLATION

composer require corneltek/pux "2.0.x-dev"

SYNOPSIS

The routing usage is dead simple:

require 'vendor/autoload.php'; // use PCRE patterns you need Pux\PatternCompiler class.
use Pux\RouteExecutor;

class ProductController {
    public function listAction() {
        return 'product list';
    }
    public function itemAction($id) { 
        return "product $id";
    }
}
$mux = new Pux\Mux;
$mux->any('/product', ['ProductController','listAction']);
$mux->get('/product/:id', ['ProductController','itemAction'] , [
    'require' => [ 'id' => '\d+', ],
    'default' => [ 'id' => '1', ]
]);
$mux->post('/product/:id', ['ProductController','updateAction'] , [
    'require' => [ 'id' => '\d+', ],
    'default' => [ 'id' => '1', ]
]);
$mux->delete('/product/:id', ['ProductController','deleteAction'] , [
    'require' => [ 'id' => '\d+', ],
    'default' => [ 'id' => '1', ]
]);

// If you use ExpandableController, it will automatically expands your controller actions into a sub-mux
$mux->mount('/page', new PageController);

$submux = new Pux\Mux;
$submux->any('/bar');
$mux->mount('/foo',$submux); // mount as /foo/bar

// RESTful Mux Builder
$builder = new RESTfulMuxBuilder($mux, [ 'prefix' => '/=' ]);
$builder->addResource('product', new ProductResourceController); // expand RESTful resource point at /=/product
$mux = $builder->build();


if ($route = $mux->dispatch('/product/1')) {
    $response = RouteExecutor::execute($route);

    $responder = new Pux\Responder\SAPIResponder();
    // $responder->respond([ 200, [ 'Content-Type: text/plain' ], 'Hello World' ]);
    $responder->respond($response);
}

Mux

Mux is where you define your routes, and you can mount multiple mux to a parent one.

$mainMux = new Mux;

$pageMux = new Mux;
$pageMux->any('/page1', [ 'PageController', 'page1' ]);
$pageMux->any('/page2', [ 'PageController', 'page2' ]);

// short-hand syntax
$pageMux->any('/page2', 'PageController:page2'  );

$mainMux->mount('/sub', $pageMux);

foreach( ['/sub/page1', '/sub/page2'] as $p ) {
    $route = $mainMux->dispatch($p);

    // The $route contains [ pcre (boolean), path (string), callback (callable), options (array) ]
    list($pcre, $path, $callback, $options) = $route;
}

Methods

  • Mux->add( {path}, {callback array or callable object}, { route options })
  • Mux->post( {path}, {callback array or callable object}, { route options })
  • Mux->get( {path}, {callback array or callable object}, { route options })
  • Mux->put( {path}, {callback array or callable object}, { route options })
  • Mux->any( {path}, {callback array or callable object}, { route options })
  • Mux->delete( {path}, {callback array or callable object}, { route options })
  • Mux->mount( {path}, {mux object}, { route options })
  • Mux->length() returns length of routes.
  • Mux->export() returns Mux constructor via __set_state static method in php code.
  • Mux->dispatch({path}) dispatch path and return matched route.
  • Mux->getRoutes() returns routes array.
  • Mux::__set_state({object member array}) constructs and returns a Mux object.

Sorting routes

You need to sort routes when not using compiled routes, it's because pux sorts longer path to front:

$pageMux = new Mux;
$pageMux->add('/', [ 'PageController', 'page1' ]);
$pageMux->add('/pa', [ 'PageController', 'page1' ]);
$pageMux->add('/page', [ 'PageController', 'page1' ]);
$pageMux->sort();

This sorts routes to:

/page
/pa
/

So pux first compares /page, /pa, than /.

Different String Comparison Strategies

When expand is enabled, the pattern comparison strategy for strings will match the full string.

When expand is disabled, the pattern comparison strategy for strings will match the prefix.

RouteRequest

RouteRequest maintains the information of the current request environment, it also provides some constraint checking methods that helps you to identify a request, e.g.:

if ($request->queryStringMatch(...)) {

}
if ($request->hostEqual('some.dev')) {

}
if ($request->pathEqual('/foo/bar')) {

}
use Pux\Environment;
$env = Environment::createFromGlobals();
$request = RouteRequest::createFromEnv($env);

if ($route = $mux->dispatchRequest($request)) {

}

APCDispatcher

Although Pux\Mux is already fast, you can still add APCDispatcher to boost the performance, which is to avoid re-lookup route.

This is pretty useful when you have a lot of PCRE routes.

use Pux\Dispatcher\APCDispatcher;
$dispatcher = new APCDispatcher($mux, array(
    'namespace' => 'app_',
    'expiry' => ...,
));
$route = $dispatcher->dispatch('/request/uri');
var_dump($route);

Controller

Pux provides the ability to map your controller methods to paths automatically, done either through a simple, fast controller in the C extension or its pure PHP counterpart:

class ProductController extends \Pux\Controller
{
    // translate to path ""
    public function indexAction() { }

    // translate to path "/add"
    public function addAction() { }

    // translate to path "/del"
    public function delAction() { }
}

$mux = new Pux\Mux;
$submux = $controller->expand();
$mux->mount( '/product' , $submux );

// or even simpler
$mux->mount( '/product' , $controller);

$mux->dispatch('/product');       // ProductController->indexAction
$mux->dispatch('/product/add');   // ProductController->addAction
$mux->dispatch('/product/del');   // ProductController->delAction

You can also use @Route and @Method annotations to override the default \Pux\Controller::expand() functionality:

class ProductController extends \Pux\Controller
{
    /**
     * @Route("/all")
     * @Method("GET")
     */
    public function indexAction() {
        // now available via GET /all only
    }
    
    /**
     * @Route("/create")
     * @Method("POST")
     */
    public function addAction() {
        // now available via POST /create only
    }
    
    /**
     * @Route("/destroy")
     * @Method("DELETE")
     */
    public function delAction() {
        // now available via DELETE /destroy only
    }
}

This is especially helpful when you want to provide more specific or semantic (e.g., HTTP method-specific) actions. Note that by default, expanded controller routes will be available via any HTTP method - specifying @Method will restrict it to the provided method.

  • Pux\Controller::expand() returns an instance of \Pux\Mux that contains the controller's methods mapped to URIs, intended to be mounted as a sub mux in another instance of \Pux\Mux.

Route RouteExecutor

Pux\RouteExecutor executes your route by creating the controller object, and calling the controller action method.

Route executor take the returned route as its parameter, you simply pass the route to executor the controller and get the execution result.

Here the simplest example of the usage:

use Pux\RouteExecutor;
$mux = new Pux\Mux;
$mux->any('/product/:id', ['ProductController','itemAction']);
$route = $mux->dispatch('/product/1');
$result = RouteExecutor::execute($route);

You can also define the arguments to the controller's constructor method:

class ProductController extends Pux\Controller {
    public function __construct($param1, $param2) {
        // do something you want
    }
    public function itemAction($id) {
        return "Product $id";
    }
}

use Pux\RouteExecutor;
$mux = new Pux\Mux;
$mux->any('/product/:id', ['ProductController','itemAction'], [ 
    'constructor_args' => [ 'param1', 'param2' ],
]);
$route = $mux->dispatch('/product/1');
$result = RouteExecutor::execute($route); // returns "Product 1"

Dispatching Strategy

There are two route dispatching strategies in Pux while Symfony/Routing only provides PCRE pattern matching:

  1. Plain string comparison.
  2. PCRE pattern comparison.

You've already knew that PCRE pattern matching is slower than plain string comparison, although PHP PCRE caches the compiled patterns.

The plain string comparison is designed for static routing paths, it improves the performance while you have a lot of simple routes.

The PCRE pattern comparison is used when you have some dynamic routing paths, for example, you can put some place holders in your routing path, and pass these path arguments to your controller later.

Pux sorts and compiles your routes to single cache file, it also uses longest matching so it sorts patterns by pattern length in descending order before compiling the routes to cache.

Pux uses indexed array as the data structure for storing route information so it's faster.

Routing Path Format

Static route:

/post

PCRE route:

/post/:id                  => matches /post/33

PCRE route with optional pattern:

/post/:id(/:title)         => matches /post/33, /post/33/post%20title
/post/:id(\.:format)       => matches /post/33, /post/33.json .. /post/33.xml

Q & A

Why It's Faster

  • Pux uses simpler data structure (indexed array) to store the patterns and flags. (In PHP internals, zend_hash_index_find is faster than zend_hash_find).

  • When matching routes, symfony uses a lot of function calls for each route:

    https://github.com/symfony/Routing/blob/master/Matcher/UrlMatcher.php#L124

    Pux fetches the pattern from an indexed-array:

    https://github.com/c9s/Pux/blob/master/src/Pux/Mux.php#L189

  • Even you enabled APC or other bytecode cache extension, you are still calling methods and functions in the runtime. Pux reduces the route building to one static method call. __set_state.

  • Pux separates static routes and dynamic routes automatically, Pux uses hash table to look up static routes without looping the whole route array.

  • Pux\Mux is written in C extension, method calls are faster!

  • With C extension, there is no class loading overhead.

  • Pux compiles your routes to plain PHP array, the compiled routes can be loaded very fast. you don't need to call functions to register your routes before using it.

Why It's Here

Most of us use a lot of machines to run our applications, however, it uses too much energy and too many resources.

Some people thinks routing is not the bottleneck, the truth is this project does not claim routing is the bottleneck.

Actually the "bottleneck" is always different in different applications, if you have a lot of heavy db requests, then your bottleneck is your db; if you have a lot of complex computation, then the bottleneck should be your algorithm.

You might start wondering since the bottleneck is not routing, why do we implement route dispatcher in C extension? The answer is simple, if you put a pure PHP routing component with some empty callbacks and use apache benchmark tool to see how many requests you can handle per second, you will find out the routing component consumes a lot of computation time and the request number will decrease quite a few. (and it does nothing, all it does is ... just routing)

Pux tries to reduce the overheads of loading PHP classes and the runtime method/function calls, and you can run your application faster without the overheads.

Pros & Cons of Grouped Pattern Matching Strategy

An idea of matching routes is to combine all patterns into one pattern and compare the given path with pcre_match in one time.

However this approach does not work if you have optional group or named capturing group, the pcre_match can not return detailed information about what pattern is matched if you use one of them.

And since you compile all patterns into one, you can't compare with other same patterns with different conditions, for example:

/users  # GET
/users  # POST
/users  # with HTTP_HOST=somedomain

The trade off in Pux is to compare routes in sequence because the same pattern might be in different HTTP method or different host name.

The best approach is to merge & compile the regexp patterns into a FSM (Finite state machine), complex conditions can also be merged into this FSM, and let this FSM to dispatch routes. And this is the long-term target of Pux.

Contributing

Testing XHProf Middleware

Define your XHPROF_ROOT in your phpunit.xml, you can copy phpunit.xml.dist to phpunit.xml, for example:

  <php>
    <env name="XHPROF_ROOT" value="/Users/c9s/src/php/xhprof"/>
  </php>

Hacking Pux C extension

  1. Discuss your main idea on GitHub issue page.

  2. Fork this project and open a branch for your hack.

  3. Development Cycle:

     cd ext
     ./compile
     ... hack hack hack ...
    
     # compile and run phpunit test
     ./compile && ./test -- --debug tests/Pux/MuxTest.php
    
     # use lldb to debug extension code
     ./compile && ./test -l -- tests/Pux/MuxTest.php
    
     # use gdb to debug extension code
     ./compile && ./test -g -- tests/Pux/MuxTest.php
    
  4. Commit!

  5. Send pull request and describe what you've done and what is changed.

More Repositories

1

bbgo

The modern cryptocurrency trading bot framework written in Go.
Go
1,209
star
2

r3

libr3 is a high-performance path dispatching library. It compiles your route paths into a prefix tree (trie). By using the constructed prefix trie in the start-up time, you may dispatch your routes with efficiency
C
799
star
3

goprocinfo

Linux /proc info parser for Go
Go
725
star
4

CLIFramework

A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!
PHP
433
star
5

c6

Compile SASS Faster ! C6 is a SASS-compatible compiler
Go
430
star
6

gomon

Monitor for any changes in your go package and automatically restart commands (run, build, server or anything)
Go
214
star
7

vikube.vim

Operating Kubernetes Cluster from Vim, in Vim
Vim Script
197
star
8

Vimana

Vimana is an easy to use system for searching , installing, and downloading vim script. Vimana provides a command-line interface such like aptitude programe on Debian linux, for you to search , download , install , upgrade scripts from http://www.vim.org (vimonline site).
Perl
183
star
9

guts

Guts is a new language beyonds PHP.
Go
156
star
10

GetOptionKit

An object-oriented option parser library for PHP, which supports type constraints, flag, multiple flag, multiple values, required value checking
PHP
144
star
11

SQLBuilder

A powerful, fast, cross-platform SQL Builder for PHP. Convert your structured data into SQL queries with a fluent style interface and targeting on all the mainstream database (MySQL, PostgreSQL, SQLite)
PHP
142
star
12

h3

The Fast HTTP header parser library
C
130
star
13

perlomni.vim

perl omnicompletion for vim (including base class function compleltions .. etc)
Vim Script
128
star
14

github-taiwan

Taiwan Developers on Github
Perl
119
star
15

Roller

A simple, fast router for PHP5.3/4, support APC cache, RESTful, highly extendable and flexible.
PHP
86
star
16

hypergit.vim

This git plugin provides many awesome features so that you don't need to type commands anymore..
Vim Script
61
star
17

App-gh

GitHub Command-line Utility.
Perl
54
star
18

AssetKit

A Modular Asset Toolkit for PHP Applications
HTML
52
star
19

fsrename

FSRename V2 - A simple, powerful rename tool supports complex filtering
Go
51
star
20

xarray

The missing PHP array functions you are looking for, implemented in extension
C
42
star
21

ts-webpack-starter

Template project based on TypeScript, Typings, Babel and Webpack
JavaScript
41
star
22

GenPHP

A Powerful,Flexible Code Generator for PHP, can generate anything what you want for your project.
PHP
40
star
23

CodeGen

Transform your dynamic calls to static calls!
PHP
38
star
24

PHPRelease

PHPRelease manages your package release process.
PHP
32
star
25

requestgen

request builder generator for Go!
Go
32
star
26

cpan.vim

vim plugin for perl hackers. for you to search installed module/all modules and integrated with perldoc window
Vim Script
30
star
27

php-ext-skeleton

The minimal PHP extension skeleton
C
29
star
28

reducer

Fast Map & Reduce php7 extension for large array
C
27
star
29

Plack-Middleware-OAuth

Plack Middleware for OAuth1 and OAuth2
Perl
27
star
30

goenv

Go project environment builder - build isolated workspace for your go project
27
star
31

phpunit.vim

phpunit plugin for Vim editor
Vim Script
25
star
32

callbackgen

callbackgen generates callback pattern for your callback fields.
Go
25
star
33

typeloy

typeloy is a meteor application deployment tool written in typescript.
TypeScript
25
star
34

vim-dev-plugin

A Vim plugin for developing VimL.
Vim Script
25
star
35

cpansearch

CPAN module search in C.
C
24
star
36

vim-makefile

A lightweight non-dependency Makefile for install, uninstall, bundle, distribute Vim plugin scripts.
Vim Script
24
star
37

GoTray

Go application manager in your system status bar. (for Mac OS X)
24
star
38

gsession.vim

gsession.vim saves your session files into the same directory (~/.vim/session/) by default. and auto-detect your session file to load session file when you are opening vim editor without arguments.
Vim Script
24
star
39

FastCommit

Integrating GIT commit flow with your own editor easily!
23
star
40

zh-stroke-data

ๅธธ็”จๅœ‹ๅญ—ๆจ™ๆบ–ๅญ—้ซ”็ญ†ๅŠƒ XML ่ณ‡ๆ–™ๆช”
JavaScript
22
star
41

WireRoom

Collaborative Chatroom For Hackers
JavaScript
20
star
42

gatsby

Gatsby Database Toolkit For Go (ORM, SQL Builder and SQLUtils)
Go
20
star
43

SimpleBench

SimpleBench provides suckless benchmark tools for PHP5.3
PHP
20
star
44

WebUI

Abstract PHP interface for building common HTML components with microdata
PHP
20
star
45

markdown-git-wiki

This is a pure git wiki (not a web server or web app), this utility only provides the functionbility of translating markdown pages into web pages. links between pages can be named by "[[Link]]". so your git wiki is just a git repository.
Perl
19
star
46

gitorbit

GitHub-like Git Server, let you control the permission via mongodb or LDAP
Go
18
star
47

jira.sh

JIRA Client for Bash Scripts
Shell
18
star
48

perldoc-zhtw-translation

Perldoc Translation in zh-tw
Perl
18
star
49

LazyBone

MicroFramework: LazyRecord + BackBone + Roller RESTful Router
JavaScript
18
star
50

php-r3

high performance r3 router extension for PHP
C
17
star
51

colorselector.vim

provide emacs-like colorscheme selector buffer.
Makefile
17
star
52

jchash

Jump Consistent Hashing Algorithm implemented in PHP 7 Extension
C
16
star
53

ClassMap

Generate class mapping file in PHP, to improve classloader performance.
PHP
16
star
54

router-benchmark

PHP Router Benchmark
PHP
14
star
55

rockhopper

rockhopper is an embeddable migration tool written by Go
Go
14
star
56

go-aes-crypt

Go
13
star
57

php-FastRequire

SPL class loader is slow! Now you can skip the SPL functions to load your minimal class requirements directly.
13
star
58

GrindKit

PHP GrindKit for reading cachegrind compatible file.
PHP
13
star
59

MiniPear

MiniPear creates local pear channel mirrors for offline usage.
PHP
12
star
60

simple-commenter.vim

simple commenter plugin
Vim Script
11
star
61

cascading.vim

Vim Script
11
star
62

ConfigKit

Toolkit for Config Files, use fast but readable YAML config file for your PHP project.
PHP
11
star
63

ClassTemplate

Class template for PHP
PHP
11
star
64

umobi

ยตMobi - Micro Mobile Web Framework for Smartphones & Tablets.
JavaScript
10
star
65

xfile

PHP Extension for file operations
C
10
star
66

PJSON

PJSONEncoder implements a JSON encoder with PHP object to JavaScript object translation support.
PHP
10
star
67

kubernetes-term

Connecting xterm.js to kubernetes exec spdy stream with socket.io
Go
9
star
68

perl-poppler

basic porting of poppler
Perl
9
star
69

phpkmp

Knuth-Morris-Pratt algorithm implemented in C, PHP and PHP Extension
C
9
star
70

PerlTW-Planet

Perl Taiwan Planet
CSS
9
star
71

vagrant-kubeadm

Vagrant for kubeadm
Shell
8
star
72

sid

Sequential ID generator as a micro-service, implemented in Go
Go
8
star
73

Git-Release

A Git Release Manager
Perl
8
star
74

ZLogger

A Simple Logger for PHP based on ZeroMQ
PHP
8
star
75

d3-kmeans

A simple, lightweight, single-dimension k-means clustering algorithm implemented in javascript for d3.
JavaScript
8
star
76

alpine-dlib

base image for dlib application
Shell
8
star
77

lftp-sync.vim

lftp sync plugin for vim.
Vim Script
8
star
78

vimomni.vim

a better completion for VimL.
Vim Script
8
star
79

requestgen-tutorial

Go
8
star
80

universal

The general purpose standard library for PHP.
PHP
8
star
81

glusterfs-deploy

Shell
7
star
82

inflect

Inflector for Go
Go
7
star
83

taipei.pm

Taipei.pm
Perl
7
star
84

ssh-authorizedkey

AuthorizedKey Encoder implemented in Go
Go
7
star
85

chrome-extension-template

7
star
86

action-js

The powerful javascript library for connecting form components with backend protocols.
JavaScript
7
star
87

bufexplorer

Vim Script
7
star
88

more.vim

ไธ€็”จๅฐฑๆ„›ไธŠ็š„ไธญๆ–‡ๅ‡ๆ–‡็”ข็”Ÿๅ™จไน‹ Vim Plugin
Vim Script
7
star
89

c9s

7
star
90

Kendo

The Powerful Access Control Framework
PHP
7
star
91

CacheKit

Generic cache interface for FileSystem cache, Memcached, ApcCache, ... etc
PHP
7
star
92

VersionKit

Version String Utilities
PHP
7
star
93

PHPUnit_TestMore

let you define Test::More-like unit tests and base on the great PHPUnit testing framework.
PHP
7
star
94

dlib-serving

Run dlib model inference as a gRPC server
CMake
7
star
95

CurlKit

A tiny curl based library for managing request/response/download task.
PHP
7
star
96

zhwrap.vim

Chinese text wrapping vim plugin.
Vim Script
6
star
97

go-duck

Duck Typing for Go
Go
6
star
98

model-serving-proto

gRPC protobuf files that define the common model serving interface
Python
6
star
99

OAuthProvider

PHP
6
star
100

php-fileutil

Fast File Utility Functions in PHP Extension and Pure PHP.
C
6
star