PHPackages                             jetz1nn/simple-router - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. jetz1nn/simple-router

ActiveLibrary[Framework](/categories/framework)

jetz1nn/simple-router
=====================

Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.

5.0.0.2(3y ago)010MITPHPPHP &gt;=7.1

Since Oct 11Pushed 3y agoCompare

[ Source](https://github.com/jetz1nn/simple-php-router)[ Packagist](https://packagist.org/packages/jetz1nn/simple-router)[ RSS](/packages/jetz1nn-simple-router/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (6)Versions (251)Used By (0)

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:**

```
SimpleRouter::get('/', function() {
    return 'Hello world';
});
```

### Support the project

[](#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](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=NNX4D2RUSALCN).

Table of Contents
-----------------

[](#table-of-contents)

- [Getting started](#getting-started)
    - [Notes](#notes-1)
    - [Requirements](#requirements)
    - [Features](#features)
    - [Installation](#installation)
        - [Setting up Apache](#setting-up-apache)
        - [Setting up Nginx](#setting-up-nginx)
        - [Setting up IIS](#setting-up-iis)
        - [Configuration](#configuration)
        - [Helper functions](#helper-functions)
- [Routes](#routes)
    - [Basic routing](#basic-routing)
        - [Class hinting](#class-hinting)
        - [Available methods](#available-methods)
        - [Multiple HTTP-verbs](#multiple-http-verbs)
    - [Route parameters](#route-parameters)
        - [Required parameters](#required-parameters)
        - [Optional parameters](#optional-parameters)
        - [Regular expression constraints](#regular-expression-constraints)
        - [Regular expression route-match](#regular-expression-route-match)
        - [Custom regex for matching parameters](#custom-regex-for-matching-parameters)
    - [Named routes](#named-routes)
        - [Generating URLs To Named Routes](#generating-urls-to-named-routes)
    - [Router groups](#router-groups)
        - [Middleware](#middleware)
        - [Namespaces](#namespaces)
        - [Subdomain-routing](#subdomain-routing)
        - [Route prefixes](#route-prefixes)
    - [Partial groups](#partial-groups)
    - [Form Method Spoofing](#form-method-spoofing)
    - [Accessing The Current Route](#accessing-the-current-route)
    - [Other examples](#other-examples)
- [CSRF-protection](#csrf-protection)
    - [Adding CSRF-verifier](#adding-csrf-verifier)
    - [Getting CSRF-token](#getting-csrf-token)
    - [Custom CSRF-verifier](#custom-csrf-verifier)
    - [Custom Token-provider](#custom-token-provider)
- [Middlewares](#middlewares)
    - [Example](#example-1)
- [ExceptionHandlers](#exceptionhandlers)
    - [Handling 404, 403 and other errors](#handling-404-403-and-other-errors)
    - [Using custom exception handlers](#using-custom-exception-handlers)
        - [Prevent merge of parent exception-handlers](#prevent-merge-of-parent-exception-handlers)
- [Urls](#urls)
    - [Get the current url](#get-the-current-url)
    - [Get by name (single route)](#get-by-name-single-route)
    - [Get by name (controller route)](#get-by-name-controller-route)
    - [Get by class](#get-by-class)
    - [Using custom names for methods on a controller/resource route](#using-custom-names-for-methods-on-a-controllerresource-route)
    - [Getting REST/resource controller urls](#getting-restresource-controller-urls)
    - [Manipulating url](#manipulating-url)
    - [Useful url tricks](#useful-url-tricks)
- [Input &amp; parameters](#input--parameters)
    - [Using the Input class to manage parameters](#using-the-input-class-to-manage-parameters)
        - [Get single parameter value](#get-single-parameter-value)
        - [Get parameter object](#get-parameter-object)
        - [Managing files](#managing-files)
        - [Get all parameters](#get-all-parameters)
        - [Check if parameters exists](#check-if-parameters-exists)
- [Events](#events)
    - [Available events](#available-events)
    - [Registering new event](#registering-new-event)
    - [Custom EventHandlers](#custom-eventhandlers)
- [Advanced](#advanced)
    - [Disable multiple route rendering](#disable-multiple-route-rendering)
    - [Restrict access to IP](#restrict-access-to-ip)
    - [Setting custom base path](#setting-custom-base-path)
    - [Url rewriting](#url-rewriting)
        - [Changing current route](#changing-current-route)
        - [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
        - [Adding routes manually](#adding-routes-manually)
    - [Custom class-loader](#custom-class-loader)
        - [Integrating with php-di](#Integrating-with-php-di)
    - [Parameters](#parameters)
    - [Extending](#extending)
- [Help and support](#help-and-support)
    - [Common issues and fixes](#common-issues-and-fixes)
        - [Multiple routes matches? Which one has the priority?](#multiple-routes-matches-which-one-has-the-priority)
        - [Parameters won't match or route not working with special characters](#parameters-wont-match-or-route-not-working-with-special-characters)
        - [Using the router on sub-paths](#using-the-router-on-sub-paths)
    - [Debugging](#debugging)
        - [Creating unit-tests](#creating-unit-tests)
        - [Debug information](#debug-information)
        - [Benchmark and log-info](#benchmark-and-log-info)
    - [Reporting a new issue](#reporting-a-new-issue)
        - [Procedure for reporting a new issue](#procedure-for-reporting-a-new-issue)
        - [Issue template](#issue-template)
    - [Feedback and development](#feedback-and-development)
        - [Contribution development guidelines](#contribution-development-guidelines)
- [Credits](#credits)
    - [Sites](#sites)
    - [License](#license)

---

Getting started
===============

[](#getting-started)

Add the latest version of the simple-router project running this command.

```
composer require pecee/simple-router

```

Notes
-----

[](#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 [here](https://github.com/skipperbent/simple-router-demo). 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:

**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
------------

[](#requirements)

- PHP 7.1 or greater (version 3.x and below supports PHP 5.5+)
- PHP JSON extension enabled.

Features
--------

[](#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` and `FILE` values.
- IP based restrictions.
- Easily extendable.

Installation
------------

[](#installation)

1. Navigate to your project folder in terminal and run the following command:

```
composer require pecee/simple-router
```

### Setting up Nginx

[](#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.

```
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

```

### Setting up Apache

[](#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

[](#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).

```
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1

```

### Setting up IIS

[](#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

[](#webconfig-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 `` section inside the `` branch.

```

```

#### Troubleshooting

[](#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 `` 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:**

```
/index.php/test/mypage.php

```

### Configuration

[](#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 `index.php` require your newly-created `routes.php` and call the `SimpleRouter::start()` 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 `index.php` file:**

```
