Download the PHP package eightsystems/simple-router without Composer
On this page you can find all versions of the php package eightsystems/simple-router. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download eightsystems/simple-router
More information about eightsystems/simple-router
Files in eightsystems/simple-router
Package simple-router
Short Description Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router. (Forked from skipperbent/simple-php-router)
License MIT
Informations about the package simple-router
simple-router
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expand-ability in mind.
With simple-router you can create a new project fast, without depending on a framework.
It only takes a few lines of code to get started:
Support the project
If you like simple-router and wish to see the continued development and maintenance of the project, please consider showing your support by buying me a coffee. Supporters will be listed under the credits section of this documentation.
You can donate any amount of your choice by clicking here.
Table of Contents
- Getting started
- Notes
- Requirements
- Features
- Installation
- Setting up Apache
- Setting up Nginx
- Setting up IIS
- Configuration
- Helper functions
- Routes
- Basic routing
- Available methods
- Multiple HTTP-verbs
- Route parameters
- Required parameters
- Optional parameters
- Regular expression constraints
- Regular expression route-match
- Custom regex for matching parameters
- Named routes
- Generating URLs To Named Routes
- Router groups
- Middleware
- Namespaces
- Subdomain-routing
- Route prefixes
- Partial groups
- Form Method Spoofing
- Accessing The Current Route
- Dependency injection
- Enabling dependency injection
- More reading
- Other examples
- Basic routing
- CSRF-protection
- Adding CSRF-verifier
- Getting CSRF-token
- Custom CSRF-verifier
- Custom Token-provider
- Middlewares
- Example
- ExceptionHandlers
- Handling 404, 403 and other errors
- Using custom exception handlers
- Urls
- Get the current url
- Get by name (single route)
- Get by name (controller route)
- Get by class
- Using custom names for methods on a controller/resource route
- Getting REST/resource controller urls
- Manipulating url
- Useful url tricks
- Input & parameters
- Using the Input class to manage parameters
- Get single parameter value
- Get parameter object
- Managing files
- Get all parameters
- Using the Input class to manage parameters
- Events
- Available events
- Registering new event
- Custom EventHandlers
- Advanced
- Url rewriting
- Changing current route
- Bootmanager: loading routes dynamically
- Adding routes manually
- Parameters
- Extending
- Url rewriting
- Help and support
- Common issues and fixes
- Multiple routes matches? Which one has the priority?
- Parameters won't match or route not working with special characters
- Using the router on sub-paths
- Debugging
- Creating unit-tests
- Debug information
- Benchmark and log-info
- Reporting a new issue
- Procedure for reporting a new issue
- Issue template
- Feedback and development
- Contribution development guidelines
- Common issues and fixes
- Credits
- Sites
- License
Getting started
THIS IS A FORK FROM skipperbent/simple-php-router, as the last commit from the original project is 2 years ago I decided to fork it, and merge the latest PRs from there
Add the latest version of the simple-router project running this command.
Notes
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
We've included a simple demo project for the router which can be found in the demo-project
folder. This project should give you a basic understanding of how to setup and use simple-php-router project.
Please note that the demo-project only covers how to integrate the simple-php-router
in a project without an existing framework. If you are using a framework in your project, the implementation might vary.
You can find the demo-project here: https://github.com/skipperbent/simple-router-demo
What we won't cover:
- How to setup a solution that fits your need. This is a basic demo to help you get started.
- Understanding of MVC; including Controllers, Middlewares or ExceptionHandlers.
- How to integrate into third party frameworks.
What we cover:
- How to get up and running fast - from scratch.
- How to get ExceptionHandlers, Middlewares and Controllers working.
- How to setup your webservers.
Requirements
- PHP 7.1 or greater (version 3.x and below supports PHP 5.5+)
- PHP JSON extension enabled.
Features
- Basic routing (
GET
,POST
,PUT
,PATCH
,UPDATE
,DELETE
) with support for custom multiple verbs. - Regular Expression Constraints for parameters.
- Named routes.
- Generating url to routes.
- Route groups.
- Middleware (classes that intercepts before the route is rendered).
- Namespaces.
- Route prefixes.
- CSRF protection.
- Optional parameters
- Sub-domain routing
- Custom boot managers to rewrite urls to "nicer" ones.
- Input manager; easily manage
GET
,POST
andFILE
values.
Installation
- Navigate to your project folder in terminal and run the following command:
Setting up Nginx
If you are using Nginx please make sure that url-rewriting is enabled.
You can easily enable url-rewriting by adding the following configuration for the Nginx configuration-file for the demo-project.
Setting up Apache
Nothing special is required for Apache to work. We've include the .htaccess
file in the public
folder. If rewriting is not working for you, please check that the mod_rewrite
module (htaccess support) is enabled in the Apache configuration.
.htaccess example
Below is an example of an working .htaccess
file used by simple-php-router.
Simply create a new .htaccess
file in your projects public
directory and paste the contents below in your newly created file. This will redirect all requests to your index.php
file (see Configuration section below).
Setting up IIS
On IIS you have to add some lines your web.config
file in the public
folder or create a new one. If rewriting is not working for you, please check that your IIS version have included the url rewrite
module or download and install them from Microsoft web site.
web.config example
Below is an example of an working web.config
file used by simple-php-router.
Simply create a new web.config
file in your projects public
directory and paste the contents below in your newly created file. This will redirect all requests to your index.php
file (see Configuration section below). If the web.config
file already exists, add the <rewrite>
section inside the <system.webServer>
branch.
Troubleshooting
If you do not have a favicon.ico
file in your project, you can get a NotFoundHttpException
(404 - not found).
To add favicon.ico
to the IIS ignore-list, add the following line to the <conditions>
group:
You can also make one exception for files with some extensions:
If you are using $_SERVER['ORIG_PATH_INFO']
, you will get \index.php\
as part of the returned value.
Example:
Configuration
Create a new file, name it routes.php
and place it in your library folder. This will be the file where you define all the routes for your project.
WARNING: NEVER PLACE YOUR ROUTES.PHP IN YOUR PUBLIC FOLDER!
In your require your newly-created and call the method. This will trigger and do the actual routing of the requests.
It's not required, but you can set SimpleRouter::setDefaultNamespace('\Demo\Controllers');
to prefix all routes with the namespace to your controllers. This will simplify things a bit, as you won't have to specify the namespace for your controllers on each route.
This is an example of a basic file:
Helper functions
We recommend that you add these helper functions to your project. These will allow you to access functionality of the router more easily.
To implement the functions below, simply copy the code to a new file and require the file before initializing the router or copy the helpers.php
we've included in this library.
Routes
Remember the file you required in your ? This file be where you place all your custom rules for routing.
Basic routing
Below is a very basic example of setting up a route. First parameter is the url which the route should match - next parameter is a Closure
or callback function that will be triggered once the route matches.
Available methods
Here you can see a list over all available routes:
Multiple HTTP-verbs
Sometimes you might need to create a route that accepts multiple HTTP-verbs. If you need to match all HTTP-verbs you can use the any
method.
We've created a simple method which matches GET
and POST
which is most commonly used:
Route parameters
Required parameters
You'll properly wondering by know how you parse parameters from your urls. For example, you might want to capture the users id from an url. You can do so by defining route-parameters.
You may define as many route parameters as required by your route:
Note: Route parameters are always encased within {} braces and should consist of alphabetic characters. Route parameters may not contain a - character. Use an underscore (_) instead.
Optional parameters
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Regular expression constraints
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
Regular expression route-match
You can define a regular-expression match for the entire route if you wish.
This is useful if you for example are creating a model-box which loads urls from ajax.
The example below is using the following regular expression: /ajax/([\w]+)/?([0-9]+)?/?
which basically just matches /ajax/
and exspects the next parameter to be a string - and the next to be a number (but optional).
Matches: /ajax/abc/
, /ajax/abc/123/
Won't match: /ajax/
Match groups specified in the regex will be passed on as parameters:
Custom regex for matching parameters
By default simple-php-router uses the \w
regular expression when matching parameters.
This decision was made with speed and reliability in mind, as this match will match both letters, number and most of the used symbols on the internet.
However, sometimes it can be necessary to add a custom regular expression to match more advanced characters like -
etc.
Instead of adding a custom regular expression to all your parameters, you can simply add a global regular expression which will be used on all the parameters on the route.
Note: If you the regular expression to be available across, we recommend using the global parameter on a group as demonstrated in the examples below.
Example
This example will ensure that all parameters use the [\w\-]+
regular expression when parsing.
You can also apply this setting to a group if you need multiple routes to use your custom regular expression when parsing parameters.
Named routes
Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition:
You can also specify names for Controller-actions:
Generating URLs To Named Routes
Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via the global url
helper-function (see helpers section):
If the named route defines parameters, you may pass the parameters as the second argument to the url
function. The given parameters will automatically be inserted into the URL in their correct positions:
For more information on urls, please see the Urls section.
Router groups
Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the SimpleRouter::group
method.
Middleware
To assign middleware to all routes within a group, you may use the middleware key in the group attribute array. Middleware are executed in the order they are listed in the array:
Namespaces
Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace
parameter in the group array:
Note
Group namespaces will only be added to routes with relative callbacks.
For example if your route has an absolute callback like \Demo\Controller\DefaultController@home
, the namespace from the route will not be prepended.
To fix this you can make the callback relative by removing the \
in the beginning of the callback.
Subdomain-routing
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route urls, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain
key on the group attribute array:
Route prefixes
The prefix
group attribute may be used to prefix each route in the group with a given url. For example, you may want to prefix all route urls within the group with admin
:
Partial groups
Partial router groups has the same benefits as a normal group, but supports parameters and are only rendered once the url has matched.
This can be extremely useful in situations, where you only want special routes to be added, when a certain criteria or logic has been met.
NOTE: Use partial groups with caution as routes added within are only rendered and available once the url of the partial-group has matched. This can cause url()
not to find urls for the routes added within.
Example:
Form Method Spoofing
HTML forms do not support PUT
, PATCH
or DELETE
actions. So, when defining PUT
, PATCH
or DELETE
routes that are called from an HTML form, you will need to add a hidden _method
field to the form. The value sent with the _method
field will be used as the HTTP request method:
Accessing The Current Route
You can access information about the current route loaded by using the following method:
Dependency injection
simple-router supports dependency injection using the php-di
library.
Dependency injection allows the framework to automatically "inject" (load) classes added as parameters. This can simplify your code, as you can avoid creating new instances of objects you are using often in your Controllers
etc.
Here's a basic example of a controller class using dependency injection:
The example above will automatically create a new instance of the User
from the $user
parameter. This means that the $user
class contains a new instance of the User
class and we won't need to create a new instance our self.
WARNING: dependency injection can have some negative impact in performance. If you experience any performance issues, we recommend disabling this functionality.
Enabling dependency injection
Dependency injection is disabled per default to avoid any performance issues.
Before enabling dependency injection, we recommend that you read the Container configuration section of the php-di documentation. This section covers how to configure php-di to different environments and speed-up the performance.
Enabling for development environment
The example below should ONLY be used on a development environment.
Please check the More reading section of the documentation for useful php-di links and tutorials.
Enabling for production environment
The example below compiles the injections, which can help speed up performance.
Note: You should change the $cacheDir
to a cache-storage within your project.
Please check the More reading section of the documentation for useful php-di links and tutorials.
More reading
For more information about dependency injection, configuration and settings - we recommend that you check the php-di documentation or some of the useful links we've gathered below.
Useful links
- php-di documentation
- Understanding dependency injection
- Best practices guide
- Configuring the container
- Definitions
Other examples
You can find many more examples in the routes.php
example-file below:
CSRF Protection
Any forms posting to POST
, PUT
or DELETE
routes should include the CSRF-token. We strongly recommend that you enable CSRF-verification on your site to maximize security.
You can use the BaseCsrfVerifier
to enable CSRF-validation on all request. If you need to disable verification for specific urls, please refer to the "Custom CSRF-verifier" section below.
By default simple-php-router will use the CookieTokenProvider
class. This provider will store the security-token in a cookie on the clients machine.
If you want to store the token elsewhere, please refer to the "Creating custom Token Provider" section below.
Adding CSRF-verifier
When you've created your CSRF-verifier you need to tell simple-php-router that it should use it. You can do this by adding the following line in your routes.php
file:
Getting CSRF-token
When posting to any of the urls that has CSRF-verification enabled, you need post your CSRF-token or else the request will get rejected.
You can get the CSRF-token by calling the helper method:
You can also get the token directly:
The default name/key for the input-field is csrf_token
and is defined in the POST_KEY
constant in the BaseCsrfVerifier
class.
You can change the key by overwriting the constant in your own CSRF-verifier class.
Example:
The example below will post to the current url with a hidden field "csrf_token
".
Custom CSRF-verifier
Create a new class and extend the BaseCsrfVerifier
middleware class provided by default with the simple-php-router library.
Add the property except
with an array of the urls to the routes you want to exclude/whitelist from the CSRF validation.
Using at the end for the url will match the entire url.
Here's a basic example on a CSRF-verifier class:
Custom Token Provider
By default the BaseCsrfVerifier
will use the CookieTokenProvider
to store the token in a cookie on the clients machine.
If you need to store the token elsewhere, you can do that by creating your own class and implementing the ITokenProvider
class.
Next you need to set your custom ITokenProvider
implementation on your BaseCsrfVerifier
class in your routes file:
Middlewares
Middlewares are classes that loads before the route is rendered. A middleware can be used to verify that a user is logged in - or to set parameters specific for the current request/route. Middlewares must implement the IMiddleware
interface.
Example
ExceptionHandlers
ExceptionHandler are classes that handles all exceptions. ExceptionsHandlers must implement the IExceptionHandler
interface.
Handling 404, 403 and other errors
If you simply want to catch a 404 (page not found) etc. you can use the Router::error($callback)
static helper method.
This will add a callback method which is fired whenever an error occurs on all routes.
The basic example below simply redirect the page to /not-found
if an NotFoundHttpException
(404) occurred.
The code should be placed in the file that contains your routes.
Using custom exception handlers
This is a basic example of an ExceptionHandler implementation (please see "Easily overwrite route about to be loaded" for examples on how to change callback).
Urls
By default all controller and resource routes will use a simplified version of their url as name.
You easily use the url()
shortcut helper function to retrieve urls for your routes or manipulate the current url.
url()
will return a Url
object which will return a string
when rendered, so it can be used safely in templates etc. but
contains all the useful helpers methods in the Url
class like contains
, indexOf
etc.
Check the Useful url tricks below.
Get the current url
It has never been easier to get and/or manipulate the current url.
The example below shows you how to get the current url:
Get by name (single route)
Get by name (controller route)
Get by class
Using custom names for methods on a controller/resource route
Getting REST/resource controller urls
Manipulating url
You can easily manipulate the query-strings, by adding your get param arguments.
You can remove a query-string parameter by setting the value to null
.
The example below will remove any query-string parameter named q
from the url but keep all others query-string parameters:
For more information please check the Useful url tricks section of the documentation.
Useful url tricks
Calling url
will always return a Url
object. Upon rendered it will return a string
of the relative url
, so it's safe to use in templates etc.
However this allow us to use the useful methods on the Url
object like indexOf
and contains
or retrieve specific parts of the url like the path, querystring parameters, host etc. You can also manipulate the url like removing- or adding parameters, changing host and more.
In the example below, we check if the current url contains the /api
part.
As mentioned earlier, you can also use the Url
object to show specific parts of the url or control what part of the url you want.
For more available methods please check the Pecee\Http\Url
class.
Input & parameters
simple-router offers libraries and helpers that makes it easy to manage and manipulate input-parameters like $_POST
, $_GET
and $_FILE
.
Using the Input class to manage parameters
You can use the InputHandler
class to easily access and manage parameters from your request. The InputHandler
class offers extended features such as copying/moving uploaded files directly on the object, getting file-extension, mime-type etc.
Get single parameter value
To quickly get a value from a parameter, you can use the input
helper function.
This will automatically trim the value and ensure that it's not empty. If it's empty the $defaultValue
will be returned instead.
Note:
This function returns a string
unless the parameters are grouped together, in that case it will return an array
of values.
Example:
This example matches both POST and GET request-methods and if name is empty the default-value "Guest" will be returned.
Get parameter object
When dealing with file-uploads it can be useful to retrieve the raw parameter object.
Search for object with default-value across multiple or specific request-methods:
The example below will return an InputItem
object if the parameter was found or return the $defaultValue
. If parameters are grouped, it will return an array of InputItem
objects.
Getting specific $_GET
parameter as InputItem
object:
The example below will return an InputItem
object if the parameter was found or return the $defaultValue
. If parameters are grouped, it will return an array of InputItem
objects.
Getting specific $_POST
parameter as InputItem
object:
The example below will return an InputItem
object if the parameter was found or return the $defaultValue
. If parameters are grouped, it will return an array of InputItem
objects.
Getting specific $_FILE
parameter as InputFile
object:
The example below will return an InputFile
object if the parameter was found or return the $defaultValue
. If parameters are grouped, it will return an array of InputFile
objects.
Managing files
Get all parameters
All object implements the IInputItem
interface and will always contain these methods:
getIndex()
- returns the index/key of the input.getName()
- returns a human friendly name for the input (company_name will be Company Name etc).getValue()
- returns the value of the input.
InputFile
has the same methods as above along with some other file-specific methods like:
getFilename
- get the filename.getTmpName()
- get file temporary name.getSize()
- get file size.move($destination)
- move file to destination.getContents()
- get file content.getType()
- get mime-type for file.getError()
- get file upload error.hasError()
- returnsbool
if an error occurred while uploading (ifgetError
is not 0).toArray()
- returns raw array
Events
This section will help you understand how to register your own callbacks to events in the router. It will also cover the basics of event-handlers; how to use the handlers provided with the router and how to create your own custom event-handlers.
Available events
This section contains all available events that can be registered using the EventHandler
.
All event callbacks will retrieve a EventArgument
object as parameter. This object contains easy access to event-name, router- and request instance and any special event-arguments related to the given event. You can see what special event arguments each event returns in the list below.
Name | Special arguments | Description |
---|---|---|
EVENT_ALL |
- | Fires when a event is triggered. |
EVENT_INIT |
- | Fires when router is initializing and before routes are loaded. |
EVENT_LOAD |
loadedRoutes |
Fires when all routes has been loaded and rendered, just before the output is returned. |
EVENT_ADD_ROUTE |
route |
Fires when route is added to the router. |
EVENT_REWRITE |
rewriteUrl rewriteRoute |
Fires when a url-rewrite is and just before the routes are re-initialized. |
EVENT_BOOT |
bootmanagers |
Fires when the router is booting. This happens just before boot-managers are rendered and before any routes has been loaded. |
EVENT_RENDER_BOOTMANAGER |
bootmanagers bootmanager |
Fires before a boot-manager is rendered. |
EVENT_LOAD_ROUTES |
routes |
Fires when the router is about to load all routes. |
EVENT_FIND_ROUTE |
name |
Fires whenever the findRoute method is called within the Router . This usually happens when the router tries to find routes that contains a certain url, usually after the EventHandler::EVENT_GET_URL event. |
EVENT_GET_URL |
name parameters getParams |
Fires whenever the Router::getUrl method or url -helper function is called and the router tries to find the route. |
EVENT_MATCH_ROUTE |
route |
Fires when a route is matched and valid (correct request-type etc). and before the route is rendered. |
EVENT_RENDER_ROUTE |
route |
Fires before a route is rendered. |
EVENT_LOAD_EXCEPTIONS |
exception exceptionHandlers |
Fires when the router is loading exception-handlers. |
EVENT_RENDER_EXCEPTION |
exception exceptionHandler exceptionHandlers |
Fires before the router is rendering a exception-handler. |
EVENT_RENDER_MIDDLEWARES |
route middlewares |
Fires before middlewares for a route is rendered. |
EVENT_RENDER_CSRF |
csrfVerifier |
Fires before the CSRF-verifier is rendered. |
Registering new event
To register a new event you need to create a new instance of the EventHandler
object. On this object you can add as many callbacks as you like by calling the registerEvent
method.
When you've registered events, make sure to add it to the router by calling
SimpleRouter::addEventHandler()
. We recommend that you add your event-handlers within your routes.php
.
Example:
Custom EventHandlers
EventHandler
is the class that manages events and must inherit from the IEventHandler
interface. The handler knows how to handle events for the given handler-type.
Most of the time the basic \Pecee\SimpleRouter\Handler\EventHandler
class will be more than enough for most people as you simply register an event which fires when triggered.
Let's go over how to create your very own event-handler class.
Below is a basic example of a custom event-handler called DatabaseDebugHandler
. The idea of the sample below is to logs all events to the database when triggered. Hopefully it will be enough to give you an idea on how the event-handlers work.
Advanced
Url rewriting
Changing current route
Sometimes it can be useful to manipulate the route about to be loaded.
simple-php-router allows you to easily manipulate and change the routes which are about to be rendered.
All information about the current route is stored in the \Pecee\SimpleRouter\Router
instance's loadedRoute
property.
For easy access you can use the shortcut helper function request()
instead of calling the class directly \Pecee\SimpleRouter\SimpleRouter::router()
.
Bootmanager: loading routes dynamically
Sometimes it can be necessary to keep urls stored in the database, file or similar. In this example, we want the url to load the route which the router knows, because it's defined in the file.
To interfere with the router, we create a class that implements the interface. This class will be loaded before any other rules in and allow us to "change" the current route, if any of our criteria are fulfilled (like coming from the url ).
The above should be pretty self-explanatory and can easily be changed to loop through urls store in the database, file or cache.
What happens is that if the current route matches the route defined in the index of our array, we set the route to the array value instead.
By doing this the route will now load the url instead of .
The last thing we need to do, is to add our custom boot-manager to the file. You can create as many bootmanagers as you like and easily add them in your file.
Adding routes manually
The class referenced in the previous example, is just a simple helper class that knows how to communicate with the class. If you are up for a challenge, want the full control or simply just want to create your own helper class, this example is for you.
Parameters
This section contains advanced tips & tricks on extending the usage for parameters.
Extending
This is a simple example of an integration into a framework.
The framework has it's own class which inherits from the class. This allows the framework to add custom functionality like loading a custom routes.php
file or add debugging information etc.
Help and support
This section will go into details on how to debug the router and answer some of the commonly asked questions- and issues.
Common issues and fixes
This section will go over common issues and how to resolve them.
Parameters won't match or route not working with special characters
Often people experience this issue when one or more parameters contains special characters. The router uses a sparse regular-expression that matches letters from a-z along with numbers when matching parameters, to improve performance.
All other characters has to be defined via the defaultParameterRegex
option on your route.
You can read more about adding your own custom regular expression for matching parameters by clicking here.
Multiple routes matches? Which one has the priority?
The router will match routes in the order they're added.
It's possible to render multiple routes.
If you want the router to stop when a route is matched, you simply return a value in your callback or stop the execution manually (using response()->json()
etc.).
Any returned objects that implements the __toString()
magic method will also prevent other routes from being rendered.
Using the router on sub-paths
Using the library on a sub-path like localhost/project/
is not officially supported, however it is possible to get it working quite easily.
Add an event that appends your sub-path when a new loadable route is added.
Example:
Debugging
This section will show you how to write unit-tests for the router, view useful debugging information and answer some of the frequently asked questions.
It will also covers how to report any issue you might encounter.
Creating unit-tests
The easiest and fastest way to debug any issues with the router, is to create a unit-test that represents the issue you are experiencing.
Unit-tests use a special TestRouter
class, which simulates a request-method and requested url of a browser.
The TestRouter
class can return the output directly or render a route silently.
Using the TestRouter helper
Depending on your test, you can use the methods below when rendering routes in your unit-tests.
Method | Description |
---|---|
Will render the route without returning anything. Exceptions will be thrown and the router will be reset automatically. | |
Will render the route and return any value that the route might output. Manual reset required by calling TestRouter::router()->reset() . |
|
Will render the route without resetting the router. Useful if you need to get loaded route, parameters etc. from the router. Manual reset required by calling TestRouter::router()->reset() . |
Debug information
The library can output debug-information, which contains information like loaded routes, the parsed request-url etc. It also contains info which are important when reporting a new issue like PHP-version, library version, server-variables, router debug log etc.
You can activate the debug-information by calling the alternative start-method.
The example below will start the routing an return array with debugging-information
Example:
The example above will provide you with an output containing:
Key | Description |
---|---|
url |
The parsed request-uri. This url should match the url in the browser. |
method |
The browsers request method (example: GET , POST , PUT , PATCH , DELETE etc). |
host |
The website host (example: domain.com ). |
loaded_routes |
List of all the routes that matched the url and that has been rendered/loaded. |
all_routes |
All available routes |
boot_managers |
All available BootManagers |
csrf_verifier |
CsrfVerifier class |
log |
List of debug messages/log from the router. |
router_output |
The rendered callback output from the router. |
library_version |
The version of simple-php-router you are using. |
php_version |
The version of PHP you are using. |
server_params |
List of all $_SERVER variables/headers. |
Benchmark and logging
You can activate benchmark debugging/logging by calling setDebugEnabled
method on the Router
instance.
You have to enable debugging BEFORE starting the routing.
Example:
When the routing is complete, you can get the debug-log by calling the getDebugLog()
on the Router
instance. This will return an array
of log-messages each containing execution time, trace info and debug-message.
Example:
Reporting a new issue
Before reporting your issue, make sure that the issue you are experiencing aren't already answered in the closed issues page on GitHub.
To avoid confusion and to help you resolve your issue as quickly as possible, you should provide a detailed explanation of the problem you are experiencing.
Procedure for reporting a new issue
- Go to this page to create a new issue.
- Add a title that describes your problems in as few words as possible.
- Copy and paste the template below in the description of your issue and replace each step with your own information. If the step is not relevant for your issue you can delete it.
Issue template
Copy and paste the template below into the description of your new issue and replace it with your own information.
You can check the Debug information section to see how to generate the debug-info.
### Description The library fails to render the route `/user/æsel` which contains one parameter using a custom regular expression for matching special foreign characters. Routes without special characters like `/user/tom` renders correctly. ### Steps to reproduce the error 1. Add the following route: 2. Navigate to `/user/æsel` in browser. 3. `NotFoundHttpException` is thrown by library. ### Route and/or callback for failing route *Route:* *Callback:* ### Debug info
Remember that a more detailed issue- description and debug-info might suck to write, but it will help others understand- and resolve your issue without asking for the information.
Note: please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue. Providing the necessary steps to reproduce the error within your description, adding useful debugging info etc. will help others quickly resolve the issue you are reporting.
Feedback and development
If the library is missing a feature that you need in your project or if you have feedback, we'd love to hear from you. Feel free to leave us feedback by creating a new issue.
Experiencing an issue?
Please refer to our Help and support section in the documentation before reporting a new issue.
Contribution development guidelines
-
Please try to follow the PSR-2 codestyle guidelines.
-
Please create your pull requests to the development base that matches the version number you want to change. For example when pushing changes to version 3, the pull request should use the
v3-development
base/branch. -
Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
-
When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
Credits
Sites
This is some sites that uses the simple-router project in production.
License
The MIT License (MIT)
Copyright (c) 2016 Simon Sessingø / simple-php-router
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.