-
Notifications
You must be signed in to change notification settings - Fork 0
Getting Start
Its pretty simple to use this library. You have many options to create a router, but we have a recomended pattern. However feel free to do your own way.
Actual version: v1.1.2-alpha
composer require rodri/simple-router:1.1.2-alpha
or eddit your composer.json file.
{
"require": {
"rodri/simple-router": "1.1.2-alpha"
}
}
- Installation
- Router configuration
- Http verbs
- Controller
- Middleware
- Request Object
- Response Object
- Router Dispatcher
Its necessary instatiate a object Router, I recomend you create the follow folder architecture.
├── public
│ └── index.php
├── App/
│ ├── Routes/
│ └── router.php
Inside file index.php
with your autoloader include once, you include the router.php
for use the router or create an app object to abstract this routine and call him inside index.php
.
On router.php
the follower strcuture its a good start for use the simple-router
use Rodri\SimpleRouter\Helpers\Header;
use Rodri\SimpleRouter\Router;
# Application Routers
$router = new Router();
# Header configurations
$router->headerConfigs([
Header::APPLICATION_JSON_UTF8,
]);
# Debug mode give a error handler more understandable.
$router->debug(true);
We cover almost all http verbs, however in future releases we gonna cover the others and add more status code return. The first argument of any verb method is array and the first index is the router name, its necessary add a bar in beggin of router name. The seccond paramter is a controller name and method response to respond for this kind of request.
$router->get(['/router-name'], 'Controller#method');
$router->post(['/router-name'], 'Controller#method');
$router->put(['/router-name'], 'Controller#method');
$router->patch(['/router-name'], 'Controller#method');
$router->delete(['/router-name'], 'Controller#method');
Other good use is the group router, which you can associate a base router name of others requests.
$router->group(['/base-name'], function (Router $router) {
$router->get(['/router-name'], 'Controller#method');
$router->post(['/router-name'], 'Controller#method');
$router->put(['/router-name'], 'Controller#method');
$router->patch(['/router-name'], 'Controller#method');
$router->delete(['/router-name'], 'Controller#method');
});
Now, when you call a request for https://localhost/base-name/router-name
the correspond method will gonna respond.
The controller is one of the most important member of the simple-router
. First you need set the base namespace for all controllers.
I recommend you use the follow strucuture.
├── public
│ └── index.php
├── App/
│ ├── Routes/
│ └── router.php
│ ├── Http/
│ ├── Controllers/
│ └── ExampleController.php
$router->setControllerNamespace('Rodri\SimpleRouter\App\Http\Controllers');
With the namespace set, just call the namespace and the correspond method for the router, separeted with #
simbol. We have inside the Exampe Controller a method call example, like this.
namespace Rodri\SimpleRouter\App\Http\Controllers;
use Rodri\SimpleRouter\Request;
use Rodri\SimpleRouter\Response;
class ExampleController
{
public function example(Request $request): Response
{
return new Response(['message' => 'example']);
}
}
For do a GET
request for example with a alone router.
$router->get(['/example'], 'ExampleController#example');
And with group you follow the same step.
$router->group(['/example'], function(Router $router) {
$router->get([''], 'ExampleController#example');
});
The middlewares is execution of a block code set to some router. To use a middleware you need implement the Middleware Interface.
namespace Rodri\SimpleRouter\Middlewares;
use Rodri\SimpleRouter\Request;
use Rodri\SimpleRouter\Response;
/**
* Interface Middleware
* @package Rodri\SimpleRouter\Middlewares
* @author Rodrigo Andrade
*/
interface MiddlewareInterface
{
/**
* Operate in request and return True in success case.
* @param Request $request
* @return bool|Response TRUE in success case and Response otherwise.
*/
public function run(Request $request): bool|Response;
}
And like the doc php comment say, for keep the router execution your middleware needs return true. If do you like to stop the execution of router, just return a response with some status code error and give to your client user a explanation of whats goning wrong.
Like controller I recommend the follower folder structure.
├── public
│ └── index.php
├── App/
│ ├── Routes/
│ └── router.php
│ ├── Http/
│ ├── Controllers/
│ └── ExampleController.php
│ ├── Middlewares/
│ └── ExampleMiddleware.php
$router->setMiddlewareNamespace('Rodri\SimpleRouter\App\Http\Middlewares');
Single Middleware:
$router->get(['/aloneGet',
'middleware' => 'ExampleMiddleware'
], 'RequestController#get');
Multiple Middlewares:
$router->get(['/aloneGet', 'middleware' => [
'FirstExampleMiddleware',
'SecondExampleMiddleware',
'ThirdExampleMiddleware'
], 'RequestController#get');
To group routes, you can set a middleware to whole group and for a unique method inside the group. The same way, you can use Single Middleware or Multiple Middlewares.
$router->group(['/request',
'middleware' => 'FirstExampleMiddleware'
], function (Router $router) {
$router->get(['/get',
'middleware' => 'SecondExampleMiddleware'
], 'RequestController#get');
$router->post(['/post'], 'RequestController#post');
$router->put(['/put'
'middleware' => [
'FourthExampleMiddleware',
'FifthExampleMiddleware'
]
], 'RequestController#put');
});
The main goal thought for this middleware implementation is for validate the request for example to a JWT token authentication.
The request object carry the request values like: params, body and headers infos. All methods of controller recive a Request Object.
/**
* Take the body of a request.
* @return string|bool
*/
$request->body();
/**
* Get a value from body request
* @param string $in
* @return mixed
*/
$request->input('value');
/**
* Get a router param by named param with separator ':'
* @param String $param
* @return mixed
*/
$request->param('param');
/**
* Get all params
* @return array
*/
$request->allParams();
## The methods above is not used with frequence in a controller:
/**
* Get the http verb
* @return string
*/
$request->method();
/**
* Check if a uri from a handle is equals a uri from server
* request, and split the expected params.
* @param string $uri
* @return bool
*/
$request->uri();
All controller need return a Response Object to your call otherwise you gonna have a call in looping.
Gived a method of a controller, the return need be a Response.
function example(Request $request): Response
{
return new Response();
}
If nothing is passed to be return, the default return is a empty body with status code 200.
The first argumnet of constructor is the return value, the value is gonna be passed to json
.
For example:
Send value by a POST
request:
{
"name":"Linus Torvalds"
}
This method gonna take the request with input value and set to upper case. Return it with Response Object.
function example(Request $request): Response
{
$name = $request->input('name');
return new Response(strtoupper($name), StatusCode::OK);
}
To return a error or a invalid response to router call.
function example(Request $request): Response
{
return new Response(Response::INVALID_RESPONSE);
}
The methods get, post, patch, delete its just use to set the chain of responsability of router. To effective use the router you need call the dispacher method.
/**
* Dispatch to router work call the expected handle.
*/
$router->dispach();