Updated documentation and added demo-project.

This commit is contained in:
Simon Sessingø
2016-09-26 14:37:54 +02:00
parent fab0d0641c
commit 980a4e9b6a
13 changed files with 359 additions and 3 deletions

3
.gitignore vendored
View File

@@ -1,3 +1,4 @@
.idea
composer.lock
vendor/
vendor/
demo-project/vendor

View File

@@ -32,6 +32,14 @@ The goal of this project is to create a router that is 100% compatible with the
- Custom boot managers to redirect urls to other routes
- Input manager; to manage `GET`, `POST` params.
## Installation and demo
We've included a simple demo project for the router which can be found in the `demo-project` folder.
Please refer to the demo-project documentation for further reading on how to setup and install simple-php-router:
[Link to demo documentation](demo-project/README.md)
## Initialising the router
In your ```index.php``` require your ```routes.php``` and call the ```routeRequest()``` method when all your custom routes has been loaded. This will trigger and do the actual routing of the requests.
@@ -176,8 +184,6 @@ This is a simple example of an integration into a framework.
The framework has it's own ```Router``` class which inherits from the ```SimpleRouter``` class. This allows the framework to add custom functionality.
```php
<?php
<?php
namespace Pecee;
use Pecee\Exception\RouterException;

104
demo-project/README.md Normal file
View File

@@ -0,0 +1,104 @@
# Simple PHP router demo project
This project is here to give you a basic understanding of how to setup and using simple-php-router.
Please note that this demo-project only covers how to integrate simple-php-project in a project without a framework. If you are using some sort of PHP framework in your project
the implementation might vary.
**What we won't cover:**
- How to setup a solution that fits your need. This is a basic demo to help you get started.
- How to add Controllers, Middlewares or ExceptionHandlers with cool functionality.
- How to integrate into third party frameworks.
**What we cover:**
- How to get up and running fast - from scratch.
- How to set ExceptionHandlers, Middlewares and Controllers working.
- How to setup your webservers.
## Installation
- Navigate to the `demo-project` folder and run `composer install`.
- Point your webserver to `demo-project/public`.
### Setting up Nginx
If you are using Nginx remember to enable url-rewriting.
You can easily do this by adding the following configuration for the Nginx configuration for the demo-project.
```
location / {
try_files $uri $uri/ /index.php?$query_string;
}
```
### 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 `.htaccess` support is enabled in the Apache configuration - or add the rules manually.
## Folder structure
| Folder | Description |
| ------------- |-------------|
| app |Contains projects-specific PHP classes|
| public |Public folder which are accessible through the web.|
## Notes
The demo project has it's own `Router` class implemented which extends the `SimpleRouter` class with further functionality such as
default exceptionhandlers and middlewares. This class can be useful adding functionality that are required before and after routing
occurs or add extra functionality to the router.
In this project we also use our custom router-class to autoload the `routes.php` file.
Please check the `routes.php` file in `demo-project/app` for all the urls/rules in the project.
### CSRF-verifier
We've added a custom CSRF-verifier middleware called `CsrfVerifier` and disabled CSRF checks for all calls to `/api/*`.
### Exception handlers
The included `CustomExceptionHandler` class returns a json response for errors received on calls to `/api/*` or otherwise just forms a simple formatted error response.
### Middlewares
`ApiVerification` class is added to all calls to `/api/*`. This simple class just adds some data to the `Request` object, which is returned in one of the methods in the
`ApiController` class.
### Urls
Please see `routes.php` for all routes and rules.
| URL |
| ------------- |
| / |
| /api/demo |
| /companies |
| /companies/[id] |
| /contact |
## 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.

View File

@@ -0,0 +1,22 @@
<?php
namespace Demo\Controllers;
use Pecee\Http\Request;
class ApiController {
public function index() {
// The variable authenticated is set to true in the ApiVerification middleware class.
$request = Request::getInstance();
header('content-type: application/json');
echo json_encode([
'authenticated' => $request->authenticated
]);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace Demo\Controllers;
class DefaultController {
public function index() {
// implement
echo 'DefaultController -> index';
}
public function contact() {
echo 'DefaultController -> contact';
}
public function companies($id = null) {
echo 'DefaultController -> companies -> id: ' . $id;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Demo\Handlers;
use Pecee\Handler\IExceptionHandler;
use Pecee\Http\Request;
use Pecee\SimpleRouter\RouterEntry;
class CustomExceptionHandler implements IExceptionHandler {
public function handleError( Request $request, RouterEntry $router = null, \Exception $error) {
// Return json errors if we encounter an error on /api.
if(stripos($request->getUri(), '/api') !== false) {
header('content-type: application/json');
echo json_encode([
'error' => $error->getMessage(),
'code' => $error->getCode()
]);
die();
}
// else we just throw the error
if($error->getCode() == 404) {
die(sprintf('An error occurred (%s):<br/>%s', $error->getCode(), $error->getMessage()));
}
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Demo\Middlewares;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class ApiVerification implements IMiddleware {
public function handle(Request $request) {
// Do authentication
$request->authenticated = true;
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Demo\Middlewares;
use Pecee\Http\Middleware\BaseCsrfVerifier;
class CsrfVerifier extends BaseCsrfVerifier {
/**
* CSRF validation will be ignored on the following urls.
*/
protected $except = ['/api/*'];
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* Custom router which handles default middlewares, default exceptions and things
* that should be happen before and after the router is initialised.
*/
namespace Demo;
use Pecee\Exception\RouterException;
use Pecee\Handler\IExceptionHandler;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\SimpleRouter\RouterBase;
use Pecee\SimpleRouter\SimpleRouter;
class Router extends SimpleRouter {
protected static $defaultExceptionHandler;
protected static $defaultMiddlewares = array();
public static function start($defaultNamespace = null) {
// change this to whatever makes sense in your project
require_once 'routes.php';
// Handle exceptions
try {
if(count(static::$defaultMiddlewares)) {
/* @var $middleware \Pecee\Http\Middleware\IMiddleware */
foreach(static::$defaultMiddlewares as $middleware) {
$middleware = new $middleware();
if(!($middleware instanceof IMiddleware)) {
throw new RouterException('Middleware must be implement the IMiddleware interface.');
}
$middleware->handle(RouterBase::getInstance()->getRequest());
}
}
// Set default namespace
$defaultNamespace = '\\Demo\\Controllers';
parent::start($defaultNamespace);
} catch(\Exception $e) {
$route = RouterBase::getInstance()->getLoadedRoute();
// Otherwise use the fallback default exceptions handler
if(static::$defaultExceptionHandler !== null) {
static::loadExceptionHandler(static::$defaultExceptionHandler, $route, $e);
}
throw $e;
}
}
protected static function loadExceptionHandler($class, $route, $e) {
$class = new $class();
if(!($class instanceof IExceptionHandler)) {
throw new \ErrorException('Exception handler must be an instance of \Pecee\Handler\IExceptionHandler');
}
$class->handleError(RouterBase::getInstance()->getRequest(), $route, $e);
}
public static function defaultExceptionHandler($handler) {
static::$defaultExceptionHandler = $handler;
}
/**
* Add default middleware that will be loaded before any route
* @param string|array $middlewares
*/
public static function defaultMiddleware($middlewares) {
if(is_array($middlewares)) {
static::$defaultMiddlewares = $middlewares;
} else {
static::$defaultMiddlewares[] = $middlewares;
}
}
}

View File

@@ -0,0 +1,19 @@
<?php
/**
* This file contains all the routes for the project
*/
use Demo\Router;
Router::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
Router::defaultExceptionHandler('\Demo\Handlers\CustomExceptionHandler');
Router::get('/', 'DefaultController@index')->setAlias('home');
Router::get('/contact', 'DefaultController@contact')->setAlias('contact');
Router::basic('/companies', 'DefaultController@companies')->setAlias('companies');
Router::basic('/companies/{id}', 'DefaultController@companies')->setAlias('companies');
// Api
Router::group(['prefix' => '/api', 'middleware' => 'Demo\Middlewares\ApiVerification'], function() {
Router::resource('/demo', 'ApiController');
});

View File

@@ -0,0 +1,26 @@
{
"name": "pecee/simple-router-demo",
"description": "Simple router demo project",
"keywords": [
"simple-router",
"php",
"php-simple-router"
],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.4.0",
"pecee/simple-router": "1.*"
},
"require-dev": {
},
"config": {
"preferred-install": "dist"
},
"autoload": {
"psr-4": {
"Demo\\": "app/"
}
}
}

View File

@@ -0,0 +1,5 @@
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1

View File

@@ -0,0 +1,7 @@
<?php
// load composer dependencies
require '../vendor/autoload.php';
// Start the routing
\Demo\Router::start();