Giter Site home page Giter Site logo

izniburak / php-router Goto Github PK

View Code? Open in Web Editor NEW
233.0 18.0 45.0 122 KB

PHP Router, which also has rich features like Middlewares and Controllers is simple, useful and flexible router class for PHP.

Home Page: https://github.com/izniburak/php-router/wiki

License: MIT License

PHP 100.00%
php router routing php-router php-routing

php-router's Introduction

Router

  _____  _    _ _____             _____             _            
 |  __ \| |  | |  __ \           |  __ \           | |           
 | |__) | |__| | |__) |  ______  | |__) |___  _   _| |_ ___ _ __
 |  ___/|  __  |  ___/  |______| |  _  // _ \| | | | __/ _ \ '__|
 | |    | |  | | |               | | \ \ (_) | |_| | ||  __/ |   
 |_|    |_|  |_|_|               |_|  \_\___/ \__,_|\__\___|_|   

PHP Router, which also has rich features like Middlewares and Controllers is simple and useful router class for PHP.

Tests Total Downloads Latest Stable Version Latest Unstable Version License

Features

  • Supports GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD, AJAX and ANY request methods
  • Easy access and manage Request and Response via symfony/http-foundation package.
  • Controllers support (Example: HomeController@about)
  • Before and after Route Middlewares support
  • Static Route Patterns
  • Dynamic Route Patterns
  • Easy-to-use patterns
  • Adding a new pattern supports. (with RegExp)
  • Namespaces supports.
  • Group Routing
  • Custom 404 and Exception handling
  • Debug mode (Error message open/close)

Install

To install PHP Router, You can run the following command directly at your project path in your console:

$ composer require izniburak/router

OR you can add following lines into the composer.json file manually:

{
    "require": {
        "izniburak/router": "^2.0"
    }
}

Then, run the following command:

$ composer install

Example Usage

require 'vendor/autoload.php';

use Buki\Router\Router;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$router = new Router;

// For basic GET URI
$router->get('/', function(Request $request, Response $response) {
    $response->setContent('Hello World');
    return $response;

    # OR
    # return 'Hello World!';
});

// For basic GET URI by using a Controller class.
$router->get('/test', 'TestController@main');

// For auto discovering all methods and URIs
$router->controller('/users', 'UserController');

$router->run();

Docs

Documentation page: Buki\Router Docs

Changelogs: Buki\Router Changelogs

Support

izniburak's homepage

izniburak's twitter

Licence

MIT Licence

Contributing

  1. Fork it ( https://github.com/izniburak/php-router/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

  • izniburak İzni Burak Demirtaş - creator, maintainer

php-router's People

Contributors

izniburak avatar kaiqueprazeres avatar peter279k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-router's Issues

ek ozellik

gruplarken namespace ve middleware tanimlayabilirim

bu arada ajax seyi guzel olmus

404 Not Found on Built-in Web Server

I started Built-in server on terminal with php -S localhost:8000 and it returned 404.
I saw any error with same code on xampp server.
Doesn't it support builtin web server?

Instagram gibi URL yapısını nasıl yapabilirim?

$router->get('/:any', 'mainController@main');
bu şekilde yaptım

public function main($ad)
{
	if($ad == "")
      {
		return 'Main method';
	}
	else
	{
		return 'Main method: ' . $ad ;
	}

}

Controller kısmını bu şekilde yaptım /burak olarak girince çıktıyı şu şekilde alabiliyorum
Main method: burak
fakat / bu şekilde girince sayfayı bulunamadı hatası veriyor nasıl yapabilirim yardımcı olur musunuz?

PSR-4 not supported

Output:

Opps! An error occurred.
SteamPunkEngine/Mobile/Index class is not found. Please, check file.

My routers:

$router->get('/', 'SteamPunkEngine\Mobile\Index@view_frontpage');
$router->post('/ajax/stats:updateVisitCount/', 'SteamPunkEngine\Mobile\Stats@invokeUpdateVisitCount');

My composer.json

"autoload": {
      "psr-4": {
        "SteamPunkEngine\\": "engine/"
      }
    }

File Index.php exists at www/engine/Mobile/Index.php and have valid namespace: namespace SteamPunkEngine\Mobile;

Missed Deployment tutorial

According to issue #10, we can find that this issue is about the deployment issue.

We missed that part/section on this repo.

I think it should be added and I find the two ways to solve this:

  • Using the GitHub Wiki to tell us how to deploy router to the Apache/Nginx HTTP server.
  • We can also Add Dockerfile to define the Docker container for this repo.

Add usage doc

As title, it needs to do this because I don't really know how to use the route request with Controller way.

@izniburak, can you add this usage section firstly? And I can help you to complete the tests for this package :).

Controller için birden fazla path belirleme

Yönlendiriciyi bu şekilde başlatıyorum.

$this->router = new Router([
            'paths' => [
                'controllers' => 'App/Controllers',
                'middlewares' => 'App/middlewares'
            ],
            'namespaces' => [
                'controllers' => 'App\Controllers',
                'middlewares' => 'App\Middlewares'
            ]
        ]);

Controllers klasöründen başka bir yerde de controller kullanıyorum. Bunu belirtmek için en iyi çözüm nedir?
Mesela şöyle bir App/**/Controllers kullanımın olup olmadığını merak ediyorum.

middleware in group whith version 2

I try creating a middleware in the new version, but I have some errors, I try to do it as it did in version 1.0:

$this->route->group('/panel', 'IndexController@main',['before' => 'sessionMiddleware'],  function($r){
       some code		
});

A test image

Warning on other methods

I only use GET & POST method before, but now when i try to make restful api i had a problem with the other methods like PUT, PATCH, and DELETE, it show a warning like this

Warning: preg_match(): Compilation failed: missing ) at offset 12 in
../myproject/vendor/izniburak/router/src/Router.php on line
299

What template manager for PHP do you recommend?

Hi guys, I am creating a professional project with your plugin (when I have it obviously I will give you the credits), I like it a lot for its simplicity and practicality.

I want to take the project to a more professional level. Can you recommend a template manager that will help me incorporate it with your plug-in and work without problem?

Thanks for the recommendation. Greetings.

router not find my url

This is my router config.

use Buki\Router;
$router = new Router([
    'debug' => true,
    'base_folder' => __DIR__,
    'paths' => [
        'controllers' => 'Controllers',
    ],
    'namespaces' => [
        'controllers' => 'App\Controller',
    ],
]);

$router->get('/', 'Controller@home');
$router->get('/get/:user_code', 'Controller@getUser');
$router->run();

Home route work correctly but /get/:user_code doesnt works. Router says:
Uncaught Exception: Route not found.

I dump result of preg_math at Router.php@433

var_dump(preg_match('#^' . $route . '$#', $uri, $matched), $route, $uri);

with this result:

int(0) string(19) "/get/:user_code" string(14) "/getdsadsa"

I think the uri should be /get/dsadsa?

CLI supports for generating middleware and controller templates

As title, the controller and middleware templates always need to be created by developers manually every time.

It should have the way to generate common controllers and middleware templates with CLI support.

This feature is very similar with Laravel artisan make:commands. Some useful reference is available here.

@izniburak, do you have any idea about this? Or maybe this feature can be another repository? (it's like php-router-cli)

Url Generation

Merhaba. Routerda isteklerimize isim verip url üretebilir miyiz?
Örneğin;

`
$router->get('signin','Panel@signin',['before' => 'SigninAuth'],'app.signin.view');

$url = $router->generate('app.signin.view');
`

Wrong route when run in sub-folder

Hello. I just check your code and got one issue when run with sub-folder

Example
URL: http://localhost/cms/test
cms is sub-folder

$router->get('test','Test@test');

Return Route


array(7) {
--
["router"]=>
  array(7) {
    ["route"]=>
    string(5) "/cms/test"
    ["method"]=>
    string(3) "GET"
    ["callback"]=>
    string(9) "Test@test"
    ["name"]=>
    string(9) "test.test"
    ["before"]=>
    NULL
    ["after"]=>
    NULL
    ["group"]=>
    NULL
  }

route should be only test

Using Routes On Terminal Commands

How can we use this route settings when we are running script on terminal? CodeIgniter has /path/to/index.php controller method type of usage. Do we have similiar thing in here?

routes don't work

I have the following directory tree:

project
├── app
│ ├── controllers
│ │ └── routeControllers.php
│ ├── models
│ ├── templates
│ │ └── homeTemplate.php
│ ├── pages
│ │ ├── home.php
│ │ ├── about.php
│ │ └── contact.php
├── include
│ │ ├── system.php
├── resources
├── vendor
── index.php

1.- index.php includes system.php
2.- system.php loads the libraries and calls the system controller.

<?php

	/**
	 * Requiere los controladores y librerias
	 */
	require_once __DIR__.'/../app/auto_loader.php';
	/**
	 * Requiere las librerias de composer
	 */
	require_once __DIR__.'/../vendor/autoload.php';

	require_once 'config.php';
	Use App\Controllers\route;
	$init = new route();
	$init->pages();

3.- The system controller instantiates the route controller e requires the main template:

<?php 

	namespace  App\Controllers;

	use App\Controllers\Route;


	class route{
		private $route;

		public function __construct(){
			$this->route =  new \Buki\Router();
	    }

		public function pages(){

			/**
			 * Rutas predeterminadas del sistema
			 */
			$this->route->get('/', function() {
			   echo "home";
			});

			$this->route->get('/hola/{s}', function($value) {
			    echo "error".$value;
			});

			$this->route->error(function() {
			    echo "error";
			});


			$this->route->run();
		}
	}

4.- when accessing the path / hello / world the url is not detected by the controller

image

Edit:
if I use the following structure it works without problem:

$this->route->get('/hello/:string', function($value){
  echo 'Hello, ' . $value;
});

Router yapısında multi lang?

Router içinde çoklu dil kurgusunu nasıl yapmalıyım mesela şunu denedim ancak doğru bir yaklaşım olmadı

$app->router->group('/:string/:slug', function ($router) {
    $router->get('/', function ($lang, $get){
        echo "<pre>";
        print_r($lang);
        echo "<hr>";
        print_r($get);
        echo "</pre>";
    });
});

custom errors

there isnt much explanation on how to use custom 404 errors can anyone give some insight?

How to access post request body?

If I have this form:

<form method="post" action="/register">
<input name="name">
<input name="country">
</form>

$router->post('/register', function () {
  // Is there any assigned variable to access name or country?
});

how to add middleware to a group

I have the following route controller

<?php
	namespace  App\Controllers;
	use Buki\Router;
	use App\Middlewares\sessionMiddleware;

	class route{
		private $route;


		public function __construct(){

			$this->route =  new \Buki\Router([
				'base_folder' => ROOT_PATH,
				'paths' => [
				    'controllers' => 'app/controllers',
				    'middlewares' => 'app/middlewares',
				  ],
				'namespaces' => [
				      'controllers' => 'App\Controllers',
				      'middlewares' => 'App\Middlewares',
				  ],
			]);
	    }

		public function pages(){

			/**
			 * Rutas predeterminadas del sistema
			 */
			$this->route->error(function() {
			    include_once __DIR__.'/../views/error404.php';
			});


			$this->route->get('/panel/cuenta', ['before' => 'sessionMiddleware'], 'sessionController@handle');

			$this->route->run();
		}	

	}

but I need to add the middleware to a specific route group. How is it done?:

Example:

  • /panel/cuenta
  • /panel/editar
  • /panel/favoritos
  • /panel/suscripciones
$router->group('/panel', function($r){
  $r->get('cuenta', function(){ echo 'page: panel/cuenta'; });
  $r->get('editar', function(){ echo 'page: panel/editar'; });
  $r->get('favoritos/php', function(){ echo 'page: panel/favoritos'; });
  $r->post('suscripciones', function(){ echo 'page: panel/suscripciones'; });
});

Thank you

url with subfolder not working

I am migrating my project to my server in production and I have a problem that I cannot detect.

Urls that have a subfolder do not work. For example

$this->route->get('/hello/word', function() {
 //code
});

but if it works:

$this->route->get('/hello', function() {
 //code
});

in the instance I have nothing special
$this->route = new \Buki\Router();

I share my php info if necessary.
http://18.236.228.15/phpinfo.php

this url doesn't work
http://18.236.228.15/oferta/bbc881542d2842dcc7d0b3003411c38c/director-o-directora-comercial-en-maquinas-de-bebidas-region-centro-en-cdmx

I use:

$this->route->pattern(':key', '[a-z0-9]+');
$this->route->pattern(':oferta', '[a-z0-9.-]+'); 

$this->route->get('oferta/:key/:oferta', function($key, $nombre) {
	include_once __DIRTEMPLATE__.'template.php';
});

Thanks for your answer.

PHP 8 getClass method is deprecated

Filename: src/RouterCommand.php

line near ~280

// $class = $param->getClass();

Fix:
use ReflectionClass;

$class = $param->getType() && !$param->getType()->isBuiltin()
? new ReflectionClass($param->getType()->getName())
: null;

Can I get a variable from route in middleware?

I have the following route with its respective middleware working:

	$this->route->pattern(':key', '[a-z0-9]+');
	$this->route->get('/url/path/:key', ['before' => 'thisMiddleware'],function($key) {
		//Code
	});
<?php 

namespace App\Middlewares;

use App\Controllers\sessionController,
App\Controllers\loginController,
App\Controllers\usuarioController,
App\Controllers\tools;

class thisMiddlewareMiddleware{

	public function handle(){
		echo $key;
	}

}

I need to access the "key" variable that is being obtained in the route in order to decide what to do

Tried doing the following but it arrives empty.

This is possible?
Thank you.

$this->route->get('/url/path/:key', ['before' => 'thisMiddleware::handle($key)'],function($key) {
		//Code
});

public function handle($key){
	echo $key;
}

Group specific error pages

How can I make a dashboard group specific error page?
Also how can I use a controller in an error callback

my code

$app->router->get('/', function() {
    return 'Hello world';
}');

$app->router->group('/dashboard', function($router){

    $router->get('/', function(){
        return 'Dashboard page';
    });
    
    $router->error(function() {
        die('Not found dashboard page');
    });
});

$app->router->error(function() {
    die('Not found this page');
});

use callback

$app->router->error('Home@not_found');

Xammp Localhost'ta sorun yok FTP'de sorun var sayfa bulunamıyor

Merhaba @izniburak Hocam;

$router = new Buki\Router();
Bu şekilde çağırmaktayım

Bu şekilde 3 farklı şekilde denememe rağmen olumsuz, sayfa bulunamadı diyor.
1.

$router->get('/kredi/yukle', function() {
	oturumy();
	global $db;
	echo "var";
	// include 'library/view/addbalance.php';
});
$router->post('/kredi/yukle', function() {
	oturumy();
	global $db;
	echo "var";
	// include 'library/view/addbalance.php';
});
$router->add('GET|POST|AJAX', '/kredi/yukle', function() {
	oturumy();
	global $db;
	echo "var";
	// include 'library/view/addbalance.php';
});

.htaccess dosyası

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Add customized error section on GitHub Wiki

As the issue #23 mentions about how to customized error page view.

It's possible, but there are no guide to tell developers how to do it.

That is, it misses on GitHub Wiki. And it seems that this should have new section name is like "customized error page" on GitHub Wiki.

However, I would be happy with working on this, but I have no permission to edit GitHub Wiki :).

I just create new issue to mention and track 😄.

get var

I need to get the identifier of an object through the get method. For example:

$this->route->get('/item/{item}', function() {
 some code here
});

This is possible?

Thank you.

How to attach the session to request parameter of a route?

Hi,

I don't have any previous experience about Symfony or your library. I couldn't find out how to access to session inside a route with request variable. I start a session with Symfony Session class at top of my index.php file but when I call $request->getSession(), I got an "Uncaught BadMethodCallException: Session has not been set" error.

What is the right way of working with sessions inside route functions?

Thanks.

Can I combine izniburak / php-router with friendly urls?

I have a project that I recently migrated to a router, in this project I have some friendly urls created with htaccess. Maybe the problem is not direct with php-router but I would like to know if you can help me here.

I need to create these friendly urls:

RewriteRule ^temas/ciudad1 temas?search&ciudad=1 [L]

But I can't because the plugin uses this default setting.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

In this case, as they are urls with parameters, I can't use router, because I don't want to access another template if not the same one but in a friendly way.

What do you advise me to do in these cases?

Thank you.

Problem setting up under a different file path (not project root)

Set up

On an existing website, I want to add an /api routing path. The current website does not have any prepackaged routing, and utilises a CMS for standard pages.

The API route is new and I want to create a routing system similar to Laravel without the overhead of a Framework.

Attempts

My basic set up looks like this, however I'm running into issues;

$router = new Buki\Router();


$router->get('/api', function() {
    return 'Hello World';
});

$router->get('/api/user', function() {
    return 'Hello World 2';
});

My rough folder structure looks like so, where all requests are routed towards index.php and this file requires routes.php if the path matches '/^\/api\/?(.*)/'. /public is configured as the root of the website in the htconfig

/var/www/{site name}/public/index.php
/var/www/{site name}/public/tpl/core/api
|-- routes.php
|-- \vendor

The php above works on the /api url, however it receives a 404 (from the package <h2>Opps! An error occurred.</h2> Route not found. Looks like something went wrong. Please try again.) on / or /api/user paths or any of my other tests based of the /api/... path

I can log out the $router variable (error_log(print_r([$router], true));) under either url and successfully see that the package is running and does show the 2 routes I'm testing with, but throws only a 404 not found on anything other than /api.

The package does say that I can edit the base folder using

$router = new Buki\Router([
    'base_folder' => '/api',
]);

for instance, but this doesn't seem to work.
I don't think this is necessarily an issue with the package, as I've tried about 4 other PHP packages claiming to do the same, and they all correctly register the routes I've set, they just don't seem to match any and show none of the output.

Controller Bulunamadı

Merhaba, Rota controlleri görmüyor

Dizin yapısı bu şekilde

  • app
    • Controllers
    • web.php
  • config
  • core
  • public
  • vendor
$router = new Router([
    'paths' => [
        'controllers' => 'app/Controllers',
    ],
    'namespaces' => [
        'controllers' => 'App\Controllers',
    ]
]);

Parameter Patterns

Hi izniburak, thank your contribution for our community. I try using parameter patterns feature. But it not working. It shows Object not found!. URL: '/' is working perfectly. Thank
$router->get('/', function() {
echo 'Home';
});

$router->get('/{s}', function($value)
{
echo 'Hello, ' . $value;
});

How to group links with optional parameter

For grouping I use the pattern, but the problem is that everything works only when the url is specified with the language, without the language it gives an error.

These links work

  • test.com/eng
  • test.com/eng/page
  • test.com/eng/admin/page

But these links do not work

  • test.com
  • test.com/page
  • test.com/admin/page
$patterns = array(
    ':lang' => 'ua|ru|eng|de'
);
$router->pattern($patterns);

$router->group(':lang?', function($router) {
    $router->get('/', function() {
        return 'Front';
    });

    $router->get('page', function() {
        return 'Front - page';
    });


    $router->group('admin', function($router) {
        $router->get('/', function() {
            return 'Admin';
        });

        $router->get('page', function() {
            return 'Admin - page';
        });
    });
});

How to solve this problem? Thank you in advance.

How to use middleware separately in functions in Auto-generated Routes?

Is is possible to use two different middlewares in same controller class while using auto generated routes?

for example, in following code, how can I use SomeMiddleware only on postMethod1 but not on getMethod1.

class SomeController extends Controller
{
    public $middlewareBefore = [
      SomeMiddleware::class
    ];

    public function getMethod1(Request $request)
    {
    }

    public function postMethod1(Request $request, Response $response)
    {
    }
}

Controller içinde post olmuyor?

Merhaba,
$router->controller('/?', mainController::class);
şu şekilde Auto controllers

	public function kayit()
	{
		if(isset($_POST['register'])){
			echo "kayit tamam: ";
		}
		include 'library/view/register.php';

	}

Bu şekilde yaptığımda postu görmüyor fakat register.php ye post if kontrolün yaptığımda oluyor bu sorunu çözme şansım var mı?

Static and dynamic route

hi Burak,
before thank you for class.
how to catch and use this examples;
/company/[regex] ?
or
/[regex]

send current route to middleware

I am making a modular site:

  • User module
  • Module publications
  • Gallery module
  • Social networks module
  • etc.

Each module has its own group path with its respective middleware. For example.

$this-> route-> group ('/ panel/user', function ($ r) {
 #code here
}, ['before' => 'sessionMiddleware']); 

$this-> route-> group ('/ panel/galerry', function ($ r) {
 #code here
}, ['before' => 'sessionMiddleware']); 

How can I go about sending the current route as a parameter to the middleware?

For example. With the same middleware you can validate that the user has access to the gallery group, but not to the users group.

If this is not possible, can you recommend a viable option please?

Thanks guys.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.