Refactor and reorganize entire repo
This commit is contained in:
parent
91aec2d0bc
commit
5a19471b8f
11
.gitignore
vendored
11
.gitignore
vendored
|
@ -1,14 +1,3 @@
|
|||
# OS files
|
||||
.DS_Store
|
||||
._*
|
||||
|
||||
# Compser files
|
||||
/vendor/
|
||||
|
||||
# local test environment
|
||||
/test/
|
||||
docker-build.sh
|
||||
docker-bash.sh
|
||||
docker-run.sh
|
||||
docker-rm.sh
|
||||
release.sh
|
||||
|
|
2
LICENSE
2
LICENSE
|
@ -1,6 +1,6 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2018 - 2020 SteamPixel and contributors
|
||||
Copyright (c) 2021, Splashsky and contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
134
README.md
134
README.md
|
@ -1,137 +1,55 @@
|
|||
# Simple PHP Router
|
||||
# SimpleRouter, PHP Edition
|
||||
|
||||
Hey! This is a simple and small single class PHP router that can handle the whole URL routing for your project.
|
||||
It utilizes RegExp and PHP's anonymous functions to create a lightweight and fast routing system.
|
||||
The router supports dynamic path parameters, special 404 and 405 routes as well as verification of request methods like GET, POST, PUT, DELETE, etc.
|
||||
The codebase is very small and very easy to understand. So you can use it as a boilerplate for a more complex router.
|
||||
Aloha! SimpleRouter is a super-small, lightweight, and easy-to-use router for your PHP project. It can handle any type of request, and features RegEx pattern matching for URI parameters. You can also easily define routes for 404 and 405 errors.
|
||||
|
||||
Take a look at the index.php file. As you can see the `Route::add()` method is used to add new routes to your project.
|
||||
The first argument takes the path segment. You can also use RegExp in there to parse out variables.
|
||||
All matching variables will be pushed to the handler method defined in the second argument.
|
||||
The third argument will match the request method. The default method is 'get'.
|
||||
As this implementation is very simple, it works great as boilerplate for a more complicated router if your project demands it. I created this to serve as a basic router for a small RPG game in PHP. Let me know what you use it for in the Discussions tab!
|
||||
|
||||
## Simple example:
|
||||
## Usage
|
||||
```php
|
||||
// Require the class
|
||||
include 'src\Steampixel\Route.php';
|
||||
// Either include the class...
|
||||
include 'src\Splashsky\Router.php';
|
||||
|
||||
// Use this namespace
|
||||
use Steampixel\Route;
|
||||
// Or use the namespace...
|
||||
use Splashsky\Router;
|
||||
|
||||
// Add the first route
|
||||
Route::add('/user/([0-9]*)/edit', function($id) {
|
||||
echo 'Edit user with id '.$id.'<br>';
|
||||
Router::add('/user/([0-9]*)/edit', function($id) {
|
||||
echo 'Edit user with id '.$id.'<br>';
|
||||
}, 'get');
|
||||
|
||||
// Run the router
|
||||
Route::run('/');
|
||||
Router::run('/');
|
||||
```
|
||||
|
||||
You will find a more complex example with a build in navigation in the index.php file.
|
||||
There are more complex examples in the `example` directory, in the `index.php` file.
|
||||
|
||||
## Installation using Composer
|
||||
Just run `composer require steampixel/simple-php-router`
|
||||
Than add the autoloader to your project like this:
|
||||
```php
|
||||
// Autoload files using composer
|
||||
require_once __DIR__ . '/vendor/autoload.php';
|
||||
## Installation
|
||||
|
||||
// Use this namespace
|
||||
use Steampixel\Route;
|
||||
The easiest way to use SimpleRouter is to install it in your project via Composer.
|
||||
|
||||
// Add your first route
|
||||
Route::add('/', function() {
|
||||
echo 'Welcome :-)';
|
||||
});
|
||||
|
||||
// Run the router
|
||||
Route::run('/');
|
||||
```bash
|
||||
composer require splashsky/simplerouter-php
|
||||
```
|
||||
|
||||
## Use a different basepath
|
||||
If your script lives in a subfolder (e.g. /api/v1) set this basepath in your run method:
|
||||
Otherwise, download the latest Release and use `include` or `require` in your code.
|
||||
|
||||
## Routing for subfolders
|
||||
If you're wanting to route for seperate uses (such as an api), you can create another entrypoint (in `/api/v1` for example) and pass a custom base path to the router.
|
||||
|
||||
```php
|
||||
Route::run('/api/v1');
|
||||
```
|
||||
|
||||
Do not forget to edit the basepath in .htaccess too if you are on Apache2.
|
||||
Ensure that your web server points traffic from `/api/v1` to this entrypoint appropriately.
|
||||
|
||||
## Use return instead of echo
|
||||
You don't have to use `echo` to output your content. You can also use the `return` statement. Everything that gets returned is echoed automatically.
|
||||
## Contributing
|
||||
|
||||
```php
|
||||
// Add your first route
|
||||
Route::add('/', function() {
|
||||
return 'Welcome :-)';
|
||||
});
|
||||
```
|
||||
I'm happy to look over and review any Issues or Pull Requests for this project. If you've run into a problem or have an enhancement or fix, submit it! It's my goal to answer and review everything within 48 hours.
|
||||
|
||||
## Use arrow functions
|
||||
Since PHP 7.4 you can also use arrow functions to output your content. So you can easily use variables from outside and you can write shorter code.
|
||||
Please be aware that an Arrow function must always return a value. Therefore you cannot use `echo` directly in here.
|
||||
You can find an example in index.php. However, this is deactivated, as it only works from PHP 7.4.
|
||||
## Credit
|
||||
|
||||
```php
|
||||
Route::add('/arrow/([a-z-0-9-]*)', fn($foo) => 'This is a working arrow function example. Parameter: '.$foo );
|
||||
```
|
||||
|
||||
## Return all known routes
|
||||
This is useful, for example, to automatically generate test routes or help pages.
|
||||
|
||||
```php
|
||||
$routes = Route::getAll();
|
||||
foreach($routes as $route) {
|
||||
echo $route['expression'].' ('.$route['method'].')';
|
||||
}
|
||||
```
|
||||
|
||||
On top of that you could use a library like https://github.com/hoaproject/Regex to generate working example links for the different expressions.
|
||||
|
||||
## Enable case sensitive routes, trailing slashes and multi match mode
|
||||
The second, third and fourth parameters of `Route::run('/', false, false, false);` are set to false by default.
|
||||
Using this parameters you can switch on and off several options:
|
||||
* Second parameter: You can enable case sensitive mode by setting the second parameter to true.
|
||||
* Third parameter: By default the router will ignore trailing slashes. Set this parameter to true to avoid this.
|
||||
* Fourth parameter: By default the router will only execute the first matching route. Set this parameter to true to enable multi match mode.
|
||||
|
||||
## Something does not work?
|
||||
* Don't forget to set the correct basepath as the first argument in your `run()` method and in your .htaccess file.
|
||||
* Enable mod_rewrite in your Apache2 settings, in case you're using Apache2: `a2enmod apache2`
|
||||
|
||||
## What skills do you need?
|
||||
Please be aware that for this router you need a basic understanding of PHP. Many problems stem from people lacking basic programming knowledge. You should therefore have the following skills:
|
||||
* Basic PHP Knowledge
|
||||
* Basic understanding of RegExp in PHP: https://www.guru99.com/php-regular-expressions.html
|
||||
* Basic understanding of anonymous functions and how to push data inside it: https://www.php.net/manual/en/functions.anonymous.php
|
||||
* Basic understanding of including and requiring files and how to push data to them: https://stackoverflow.com/questions/4315271/how-to-pass-arguments-to-an-included-file/5503326
|
||||
* Windows Only - Setup IIS and PHP: https://docs.microsoft.com/en-us/iis/application-frameworks/scenario-build-a-php-website-on-iis/configuring-step-1-install-iis-and-php.
|
||||
* Windows Only - Creating Websites in IIS: https://docs.microsoft.com/en-us/iis/get-started/getting-started-with-iis/create-a-web-site.
|
||||
|
||||
Please note that we are happy to help you if you have problems with this router. Unfortunately, we don't have a lot of time, so we can't help you learn PHP basics.
|
||||
|
||||
## Test setup with Docker
|
||||
I have created a little Docker test setup.
|
||||
|
||||
1. Build the image: `docker build -t simplephprouter docker/image-php-7.2`
|
||||
|
||||
2. Spin up a container
|
||||
* On Linux / Mac or Windows Powershell use: `docker run -d -p 80:80 -v $(pwd):/var/www/html --name simplephprouter simplephprouter`
|
||||
* On Windows CMD use `docker run -d -p 80:80 -v %cd%:/var/www/html --name simplephprouter simplephprouter`
|
||||
|
||||
3. Open your browser and navigate to http://localhost
|
||||
|
||||
## Test Setup in Windows using IIS
|
||||
With IIS now fully supporting PHP, this example can be run using the included web.config. The web.config has a rewrite rule, similar to the .htaccess rewrite rule, but specifically for IIS. The rewrite rule will send all incoming requests to index.php in your root. The rest is done by the simple php router.
|
||||
### Setup
|
||||
_This setup tutorial assumes you have the knowledge to create sites in IIS and set up bindings for http/https and custom DNS. If you need more information, this [article](https://docs.microsoft.com/en-us/iis/get-started/getting-started-with-iis/create-a-web-site) will help you with that part._
|
||||
1. If you haven't done so yet, install php on windows. This article [Install IIS and PHP | Microsoft Docs ](https://docs.microsoft.com/en-us/iis/application-frameworks/scenario-build-a-php-website-on-iis/configuring-step-1-install-iis-and-php) will guide you to install the required php dependencies on your windows machine.
|
||||
2. In IIS Manager, create a site and point the physical location to root of the simplePHPRouter folder. It is recommended you connect to the the physical location with an account that has "Read/Write" rights to that folder.
|
||||
3. (Optional) Create a DNS entry in your hosts file pointing 127.0.0.1 to the domain name you have used to set up the site.
|
||||
4. Browse to the newly created website and the sample site should display now.
|
||||
|
||||
## Todo
|
||||
* Create demo configuration for nginx
|
||||
Most of the code so far has been initially written by [@SteamPixel](https://github.com/steampixel), so make sure to give him a follow or a star on the original repo as well. Thanks!
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License. See LICENSE for further information.
|
||||
|
|
|
@ -1,9 +1,14 @@
|
|||
{
|
||||
"name": "steampixel/simple-php-router",
|
||||
"description": "This is a simple and small PHP router that can handel the whole url routing for your project.",
|
||||
"name": "splashsky/simplerouter-php",
|
||||
"description": "A very light, easy-to-use router for PHP apps.",
|
||||
"type": "library",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "@Splashsky",
|
||||
"email": "sky@surf.gg",
|
||||
"homepage": "https://surf.gg"
|
||||
},
|
||||
{
|
||||
"name": "Christoph Stitz",
|
||||
"email": "info@steampixel.de",
|
||||
|
@ -18,8 +23,8 @@
|
|||
"minimum-stability": "dev",
|
||||
"require": {},
|
||||
"autoload": {
|
||||
"psr-0": {
|
||||
"Steampixel": "src/"
|
||||
}
|
||||
}
|
||||
"psr-4": {
|
||||
"Splashsky\\": "src/"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,19 +0,0 @@
|
|||
FROM php:7.2-apache
|
||||
|
||||
# Enable rewrite
|
||||
RUN a2enmod rewrite
|
||||
|
||||
# Install composer
|
||||
# https://www.hostinger.com/tutorials/how-to-install-composer
|
||||
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
|
||||
RUN php composer-setup.php --install-dir=/usr/local/bin --filename=composer
|
||||
RUN php -r "unlink('composer-setup.php');"
|
||||
|
||||
# Update
|
||||
RUN apt-get update -y
|
||||
|
||||
# Install git
|
||||
RUN apt-get install git -y
|
||||
|
||||
# Install zip
|
||||
RUN apt-get install zip -y
|
|
@ -1,18 +0,0 @@
|
|||
FROM php:7.4.1-apache
|
||||
|
||||
RUN a2enmod rewrite
|
||||
|
||||
# Install composer
|
||||
# https://www.hostinger.com/tutorials/how-to-install-composer
|
||||
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
|
||||
RUN php composer-setup.php --install-dir=/usr/local/bin --filename=composer
|
||||
RUN php -r "unlink('composer-setup.php');"
|
||||
|
||||
# Update
|
||||
RUN apt-get update -y
|
||||
|
||||
# Install git
|
||||
RUN apt-get install git -y
|
||||
|
||||
# Install zip
|
||||
RUN apt-get install zip -y
|
|
@ -1,17 +1,10 @@
|
|||
<?php
|
||||
|
||||
// Use this namespace
|
||||
use Steampixel\Route;
|
||||
use Splashsky\SimpleRouter;
|
||||
|
||||
// Include router class
|
||||
include 'src/Steampixel/Route.php';
|
||||
include '../src/Splashsky/Router.php';
|
||||
|
||||
// Define a global basepath
|
||||
define('BASEPATH','/');
|
||||
|
||||
// If your script lives in a subfolder you can use the following example
|
||||
// Do not forget to edit the basepath in .htaccess if you are on apache
|
||||
// define('BASEPATH','/api/v1');
|
||||
define('BASEPATH', '/');
|
||||
|
||||
function navi() {
|
||||
echo '
|
125
src/Splashsky/Router.php
Normal file
125
src/Splashsky/Router.php
Normal file
|
@ -0,0 +1,125 @@
|
|||
<?php
|
||||
|
||||
namespace Splashsky;
|
||||
|
||||
class Router
|
||||
{
|
||||
private static array $routes = [];
|
||||
private static $pathNotFound;
|
||||
private static $methodNotAllowed;
|
||||
|
||||
public static function add(string $route, callable $callback, string $method = 'get')
|
||||
{
|
||||
self::$routes[] = [
|
||||
'route' => $route,
|
||||
'callback' => $callback,
|
||||
'method' => $method
|
||||
];
|
||||
}
|
||||
|
||||
public static function get(string $route, callable $callback)
|
||||
{
|
||||
self::add($route, $callback, 'get');
|
||||
}
|
||||
|
||||
public static function post(string $route, callable $callback)
|
||||
{
|
||||
self::add($route, $callback, 'post');
|
||||
}
|
||||
|
||||
public static function getAllRoutes()
|
||||
{
|
||||
return self::$routes;
|
||||
}
|
||||
|
||||
public static function pathNotFound(callable $callback)
|
||||
{
|
||||
self::$pathNotFound = $callback;
|
||||
}
|
||||
|
||||
public static function methodNotAllowed(callable $callback)
|
||||
{
|
||||
self::$methodNotAllowed = $callback;
|
||||
}
|
||||
|
||||
public static function run(string $basePath = '', bool $caseMatters = false, bool $trailingSlashMatters = false, bool $multimatch = false)
|
||||
{
|
||||
$basePath = rtrim($basePath, '/');
|
||||
$url = parse_url($_SERVER['REQUEST_URI']);
|
||||
$path = '/';
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
|
||||
if (isset($url['path'])) {
|
||||
if ($trailingSlashMatters) {
|
||||
$path = $url['path'];
|
||||
} else {
|
||||
if($basePath.'/' != $url['path']) {
|
||||
$path = rtrim($url['path'], '/');
|
||||
} else {
|
||||
$path = $url['path'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$path = urldecode($path);
|
||||
|
||||
$pathMatchFound = false;
|
||||
$routeMatchFound = false;
|
||||
|
||||
foreach (self::$routes as $route) {
|
||||
if ($basePath != '' && $basePath != '/') {
|
||||
$route['route'] = '('.$basePath.')'.$route['route'];
|
||||
}
|
||||
|
||||
// Add string start and end automatically
|
||||
$route['route'] = '^'.$route['route'].'$';
|
||||
|
||||
// Check path match
|
||||
if (preg_match('#'.$route['route'].'#'.($caseMatters ? '' : 'i').'u', $path, $matches)) {
|
||||
$pathMatchFound = true;
|
||||
|
||||
// Cast allowed method to array if it's not one already, then run through all methods
|
||||
foreach ((array) $route['method'] as $allowedMethod) {
|
||||
// Check method match
|
||||
if (strtolower($method) == strtolower($allowedMethod)) {
|
||||
array_shift($matches); // Always remove first element. This contains the whole string
|
||||
|
||||
if ($basePath != '' && $basePath != '/') {
|
||||
array_shift($matches); // Remove basepath
|
||||
}
|
||||
|
||||
if ($return = call_user_func_array($route['callback'], $matches)) {
|
||||
echo $return;
|
||||
}
|
||||
|
||||
$routeMatchFound = true;
|
||||
|
||||
// Do not check other routes
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Break the loop if the first found route is a match
|
||||
if($routeMatchFound && !$multimatch) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// No matching route was found
|
||||
if (!$routeMatchFound) {
|
||||
// But a matching path exists
|
||||
if ($pathMatchFound) {
|
||||
if (self::$methodNotAllowed) {
|
||||
die('Method not allowed');
|
||||
//call_user_func_array(self::$methodNotAllowed, Array($path, $method));
|
||||
}
|
||||
} else {
|
||||
if (self::$pathNotFound) {
|
||||
die('Path not found');
|
||||
//call_user_func_array(self::$pathNotFound, Array($path));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,138 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Steampixel;
|
||||
|
||||
class Route {
|
||||
|
||||
private static $routes = Array();
|
||||
private static $pathNotFound = null;
|
||||
private static $methodNotAllowed = null;
|
||||
|
||||
/**
|
||||
* Function used to add a new route
|
||||
* @param string $expression Route string or expression
|
||||
* @param callable $function Function to call if route with allowed method is found
|
||||
* @param string|array $method Either a string of allowed method or an array with string values
|
||||
*
|
||||
*/
|
||||
public static function add($expression, $function, $method = 'get'){
|
||||
array_push(self::$routes, Array(
|
||||
'expression' => $expression,
|
||||
'function' => $function,
|
||||
'method' => $method
|
||||
));
|
||||
}
|
||||
|
||||
public static function getAll(){
|
||||
return self::$routes;
|
||||
}
|
||||
|
||||
public static function pathNotFound($function) {
|
||||
self::$pathNotFound = $function;
|
||||
}
|
||||
|
||||
public static function methodNotAllowed($function) {
|
||||
self::$methodNotAllowed = $function;
|
||||
}
|
||||
|
||||
public static function run($basepath = '', $case_matters = false, $trailing_slash_matters = false, $multimatch = false) {
|
||||
|
||||
// The basepath never needs a trailing slash
|
||||
// Because the trailing slash will be added using the route expressions
|
||||
$basepath = rtrim($basepath, '/');
|
||||
|
||||
// Parse current URL
|
||||
$parsed_url = parse_url($_SERVER['REQUEST_URI']);
|
||||
|
||||
$path = '/';
|
||||
|
||||
// If there is a path available
|
||||
if (isset($parsed_url['path'])) {
|
||||
// If the trailing slash matters
|
||||
if ($trailing_slash_matters) {
|
||||
$path = $parsed_url['path'];
|
||||
} else {
|
||||
// If the path is not equal to the base path (including a trailing slash)
|
||||
if($basepath.'/'!=$parsed_url['path']) {
|
||||
// Cut the trailing slash away because it does not matters
|
||||
$path = rtrim($parsed_url['path'], '/');
|
||||
} else {
|
||||
$path = $parsed_url['path'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$path = urldecode($path);
|
||||
|
||||
// Get current request method
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
|
||||
$path_match_found = false;
|
||||
|
||||
$route_match_found = false;
|
||||
|
||||
foreach (self::$routes as $route) {
|
||||
|
||||
// If the method matches check the path
|
||||
|
||||
// Add basepath to matching string
|
||||
if ($basepath != '' && $basepath != '/') {
|
||||
$route['expression'] = '('.$basepath.')'.$route['expression'];
|
||||
}
|
||||
|
||||
// Add 'find string start' automatically
|
||||
$route['expression'] = '^'.$route['expression'];
|
||||
|
||||
// Add 'find string end' automatically
|
||||
$route['expression'] = $route['expression'].'$';
|
||||
|
||||
// Check path match
|
||||
if (preg_match('#'.$route['expression'].'#'.($case_matters ? '' : 'i').'u', $path, $matches)) {
|
||||
$path_match_found = true;
|
||||
|
||||
// Cast allowed method to array if it's not one already, then run through all methods
|
||||
foreach ((array)$route['method'] as $allowedMethod) {
|
||||
// Check method match
|
||||
if (strtolower($method) == strtolower($allowedMethod)) {
|
||||
array_shift($matches); // Always remove first element. This contains the whole string
|
||||
|
||||
if ($basepath != '' && $basepath != '/') {
|
||||
array_shift($matches); // Remove basepath
|
||||
}
|
||||
|
||||
if($return_value = call_user_func_array($route['function'], $matches)) {
|
||||
echo $return_value;
|
||||
}
|
||||
|
||||
$route_match_found = true;
|
||||
|
||||
// Do not check other routes
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Break the loop if the first found route is a match
|
||||
if($route_match_found&&!$multimatch) {
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// No matching route was found
|
||||
if (!$route_match_found) {
|
||||
// But a matching path exists
|
||||
if ($path_match_found) {
|
||||
if (self::$methodNotAllowed) {
|
||||
call_user_func_array(self::$methodNotAllowed, Array($path,$method));
|
||||
}
|
||||
} else {
|
||||
if (self::$pathNotFound) {
|
||||
call_user_func_array(self::$pathNotFound, Array($path));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,10 +1,10 @@
|
|||
DirectoryIndex index.php
|
||||
|
||||
# enable apache rewrite engine
|
||||
# Enable Apache rewrite engine
|
||||
RewriteEngine on
|
||||
|
||||
# set your rewrite base
|
||||
# Edit this in your init method too if you script lives in a subfolder
|
||||
# Set the rewrite base path
|
||||
# Pass this to the run() method too, if your entry point is in a subfolder
|
||||
RewriteBase /
|
||||
|
||||
# Deliver the folder or file directly if it exists on the server
|
5
webconfigs/readme.md
Normal file
5
webconfigs/readme.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
# Example Web Server Configs
|
||||
These are example configs you'd want to use when using SimpleRouter.
|
||||
|
||||
`.htaccess` is for Apache-based web servers. <br />
|
||||
`web.config` is for IIS/Microsoft-based web servers.
|
Loading…
Reference in New Issue
Block a user