Rhino is a php micro-framework for building fast and reliable http services, APIs, and to serve static content through an easy to configure php based routing service.
Find this project on packagist: php-rhino
- Quick Start
- Feature Tutorials
- Installation
- API Documentation
To get started quickly simply require or include one of the rhino.php
files
located in the base or lib/ folder of this framework in the index.php
file
of your application.
You can then call the exported rhino()
function to instantiate this
framework’s main application and assign the return to a variable -
conventionally named $app
.
Next use instance methods of the application object to register middleware and
routehandler. use()
registers a middleware with this application while
methods like get()
, post()
and delete()
register route handlers which
result in a final http response to the client.
Finally a call to the start()
method must be made after all components have
been registered on the application object.
<?php
require_once (dirname(__FILE__) . "/lib/rhino.php");
$app = rhino();
$app->use($jsonparse);
$app->post('/', function($req, $res) {
$name = $req->body['name'];
$res->send("Hello $name");
});
$app->get('/', function($req, $res) {
$res->send("Hello, World!");
});
$app->get('/:name', function($req, $res) {
$res->send("Hello " . $req->params['name']);
});
$app->start();
To immediately test your application open a terminal in the root folder of your application and launch a php development server by entering:
php -S localhost:5001 .
Open your favorite browser and navigate to localhost:5001/Peter
to view the
results. If you want to test the registered POST route as well you can use an
external graphical tool like Postman or simply use cURL from the terminal
with the following command:
echo '{ "name": "Charlie" }' | curl -d @- http://localhost:5001/ --header "Content-Type:application/json"
Take a look in the examples/
folder for more advanced working prototype
applications.
Most regular expressions work with route handlers.
<?php
// trigger this route handler as a middleware for all routes starting
// with `/api/`.
$app->use('/api/*', function($req, $res) {
});
// trigger this route handler for any number entered after `/api/`
$app->get('/api/[0-9]+', function($req, $res) {
});
$app->get('/api/*/name/[A-Za-z ]+', function($req, $res) {
});
Query Parameters are automatically converted to key-value pairs and
stored in the query
property of the request object.
<?php
$app->get('/', function($req, $res) {
$orderBy = $req->query['orderBy'];
$offset = $req->query['offset'];
$limit = $req->query['limit'];
});
Route parameters are defined with a colon :
in the resource route.
Route parameters and strings entered by the client in place of the
route parameters are converted to key - value pairs and stored in the
params
property of the request object.
<?php
$app->get('/api/users/:id', function($req, $res) {
$res->send("Retrieving data for user with id: {$req->params['id']}");
});
$app->get('/api/users/:lastname/:firstname', function($req, $res) {
$lastName = $req->params['lastname'];
$firstName = $req->params['firstname'];
$res->send("Loading data for $firstName $lastName");
}
Additional routers can be instantiated from the original Application
$app
instance. These routers hold most of the same methods that the
Application instance has. Secondary routers can be mounted on a
custom path on other routers or the main application.
Secondary routers are used to segment different resources into their own files and to later mount them on a common url resouce path.
// in users.php
$router = $app->router();
$router->get('/', function($req, $res) {
// do stuff
});
$router->get('/:id', function($req, $res) {
// do stuff
});
// in index.php
require_once (dirname(__file__) . '/routes/users.php');
$app->use('/api/users/', $router);
// routes registered on $router are now available on /api/users/...
Middleware is functionality that is executed as part of the
request-response cycle. The use()
method registers middleware
functions on a given path. Those middleware functions are defined like
regular route handlers but do not automatically terminate the request
response cycle after they are finished executing.
<?php
// this middleware is used to check whether the client has the required
// authentication and is executed on all routes of the 'users' resource.
$app->use('/api/users/*', function($req, $res) {
if (!$req->get('X-Token')) {
$res->status(401)->send('Access denied. No token provided.');
$res->end();
}
// authenticate some more
});
To use the built-in validator you must import
/lib/addons/validation.php
in your main index.php file.
The recommended way of installing this framework is placing the lib/
folder
in the root or vendor/
folder of your project and then requiring the main
rhino.php
file in your app’s main index.php file. That’s it - you are ready
to go.
<?php
require_once (dirname(__FILE__) . "/lib/rhino.php");
- rhino()
- Application
- router()
- start()
- Router
- get()
- post()
- put()
- delete()
- all()
- use()
- Request
- app
- headers
- get()
- body
- params
- queryString
- query
- originalUrl
- url
- method
- hostname
- port
- Response
- app
- set()
- send()
- json()
- end()
- status()
- sendStatus()
- type()
$jsonparse
Generate the request and response objects used throughout the application and return a new instance of this framework’s main Application class.
@param $options Array - optional parameter mapping of settings (see api docs)
@return Application
Application is a router that can register middleware and route handlers and
mount other routers. It inherits all methods and properties from the Router
class.
The Application class inherits two additional methods. One to start the application by iterating over this applications route $queue and one to generate a new router.
Start this application.
Iterate over all registered route queue collections, match routes and execute middleware and response callback functions.
Return a new router.
@return {Router} new router instance generated using this application.
The Router serves as a collection to which route handlers, middleware and other routers can be registered to.
The objects registered to this router are stored in the $queue collection.
This collection is traversed by the main collection until all matching routes have been found or the request response cycle has been terminated.
Numerous functions to register routes to this router are available as instance methods on this class.
Use the .use(), .get(), .post(), .put(), .delete(), and .all() methods to register routes with a router. See the api documentation for examples.
Register the provided arguments with this router’s routing $queue either as middleware or as a router according to their data type.
Optionally a url string may be provided to specify the target route or resource direction. If no url string is provided the root location will be assumed as the default route.
@param $args Array - Array of a url string, closure functions or Router.
Register provided arguments as middleware by calling the `registerRouteHandler()` function with the appropriate http method.
@param $args Array - Array of a url string and closure functions.
Register provided arguments as middleware by calling the `registerRouteHandler()` function with the appropriate http method.
@param $args Array - Array of a url string and closure functions.
The Request class holds all relevant information about a received http request and a method to conveniently retrieve http header values.
A reference to the Application instance this Request belongs to.
ArrayMap of all http headers sent with this request.
Returns the specified HTTP request header field. Argument header names and stored header keys are case-insensitive.
@param $header {string} - name of a http header.
@return {string} return the value of a specific header or null if not set.
The raw content of this request’s payload or request body represented as a
string. The request body can be automatically parsed as JSON by registering the
built-in $jsonparse
middleware on the desired routes.
A map of route parameters to parameter values.
Holds the query string sent with this request.
A map of query string parameters to query string parameter values.
The entire original recipient url used with this Request. Do not modify this url.
A copy of the original url. This field may be modified and used for app internal routing by the programmer or third party middleware / plugins.
The http method used to send this request.
Name of the host that this Request is addressed to.
The Port number that this Request is addressed to.
The Response class provides useful methods to set http response codes, write to the http response stream, and to break out of the request response cycle by ending the http response.
A reference to the Application instance this Request belongs to.
Set an http response header to a given value. This function can not be used after the http response body has been written to.
@param $header {string} http header
@param $value {string} http header value
@return Response - a reference to this response object to allow chaining.
Write a given string to the http response stream.
@param $body {string} text to write to the http response body.
@return Response - a reference to this response object to allow chaining.
Automatically convert an object, array or map to a json formatted string, set the ‘Content-Type’ http header to ‘application/json’ and write the string to the http response stream.
@param $body object - object, array or map
@return Response - a reference to this Response object to allow chaining.
End the http response by throwing a new EndResponse Exception. The http output stream closes when this function is called.
Set the http status code to the given value.
@param $code {int} http status code
@return Response - a reference to this response object to allow chaining.
Set the http status code to the given value and write the conventional status message to the response body.
@param $code {int} http status code
@return Response - a reference to this response object to allow chaining.