I’ve been working on a new project lately and I’m calling it WebPHP. I wanted something that operated somewhat like Tornado for Python.. but in PHP.
I essentially wanted some framework that could simply be dropped onto the root of a hosted server from GoDaddy or the like, and a developer could immediately map URLs using a regex-like syntax to handler classes. I found some other frameworks to do this, but a lot of them seemed tightly coupled to a front-end framework not to mention complicated to install or maintain. Hence my creation of WebPHP. WebPHP works by mapping a URL with regex style syntax like
/api/users/(.+)/? Maps to http://example.com/api/users/{anything} /api/users/jacobcalvert/profile/? Would get my profile in this example service
to some handler class that would do something with the request. The way this map is defined is shown below:
new webphp\UrlMap("/(.+)/?", array("the_variable"),'ExampleHandler', array())
WebPHP would populate a variable called “the_variable” and instantiate an object of type ExampleHandler. ExampleHandler must be a derived class of the base WebRequest class defined by WebPHP. ExampleHandler could look like:
class ExampleHandler extends webphp\WebRequest { /* * example handler for webphp */ public function get() { $this->add_header("Content-Type", "application/json"); $this->write(json_encode($this->params, JSON_UNESCAPED_SLASHES)); } public function post() { $this->add_header("Content-Type", "application/json"); $this->set_response_code(201); // 201 is the "CREATED" response -- could be used for REST impl's $this->write(json_encode($this->params, JSON_UNESCAPED_SLASHES)); } public function put() { $this->add_header("Content-Type", "application/json"); $this->write(json_encode($this->params, JSON_UNESCAPED_SLASHES)); } public function delete() { $this->set_response_code(403); $this->write(NULL); } public function head() { // just an example of adding a custom header // the HEAD verb expects just the headers back about // the requested document // or in other words, HEAD wants a GET response without the body $this->add_header("Custom-Header", "custom-value"); $this->write(NULL); } }
The WebPHP app would call the appropriate handler method depending on what HTTP verb was used in the request. If no method is defined for a verb that is used, the default return is a 501/Not Implemented response. One of the interesting features I was able to add is the ability to enforce SSL connections on specific URL maps or on entire handlers. Hop over to theĀ GitHub pageĀ for more information and to see all the classes and example.