hoben/simple-routes

Simple routing package for PHP.

dev-master 2018-04-19 15:22 UTC

This package is not auto-updated.

Last update: 2024-05-12 03:54:02 UTC


README

Author Software License

Simple and easy-to-use router built for beginners and light-weight projects.

This package is compliant with [PSR-2]

Install

Via Composer

$ composer require hoben/simple-routes

Requirements

  • PHP ^5.5.9 | >=7.0.8
  • Symfony/yaml: ^3.4

Features

  • Create routes defined in yaml files
  • You can also add routes in code with the function add of the class Router.php
  • You can filter routes by methods ( GET, POST, PUT ,DELETE,...)

Adding routes with yaml file (routes.yaml)

"Dashboard":
  url: /
  controller: indexController
  action: index
  method: GET

"Test Page":
  url: /
  controller: indexController
  action: showTest
  method: POST

"default":
  controller: defaultController
  action: show404
$router = new Router();
$router->setBasePath('my-app/'); // Example: for www.localhost/my-app
$router->setControllersPath('src/controllers/'); // Example: for controllers in www.localhost/my-app/src/controllers
$router->setConfigPath('yaml-file-path/routes.yaml') // The yaml file path
$router->match();

Adding routes with PHP code

use Hoben\SimpleRoutes\Router;

$router = new Router();

$route->add('/products', 'ProductController', 'getProducts', 'GET');
$route->add('/product', 'ProductController', 'getProduct', 'GET');
$route->add('/product', 'ProductController', 'addProduct', 'POST');
$route->add('/product', 'ProductController', 'updateProduct', 'PUT');

$router->setBasePath('my-app/'); // Example: for www.localhost/my-app
$router->setControllersPath('src/controllers/'); // Example: for controllers in www.localhost/my-app/src/controllers
$router->match();

Bonus: How to redirect all urls to index.php

Create a simple .htaccess file on your root directory if you're using Apache with mod_rewrite enabled.

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ index.php [NC,L]

If you're using nginx, setup your server section as following:

server {
	listen 80;
	server_name mywebsite.dev;
	root /var/www/mywebsite/public;

	index index.php;

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

	location ~ \.php$ {
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

		# With php5-fpm:
		fastcgi_pass unix:/var/run/php5-fpm.sock;
		fastcgi_index index.php;
		include fastcgi.conf;
		fastcgi_intercept_errors on;
	}
}

License

The MIT License (MIT). Please see License File for more information.