Convention based routing for PHP

Related tags

Routers croute
Overview

Croute

Latest Version on Packagist Software License Build Status Coverage Status SensioLabsInsight

Convention based routing for PHP based on Symfony components.

Croute is great because:

  • You don't need to maintain a routing table
  • Promotes consistent code organization
  • Allows for customization through annotations and events

Install via Composer

Via the command line:

composer.phar require thewunder/croute ~1.0

Or add the following to the require section your composer.json:

"thewunder/croute": "~1.0"

Basics

Your index.php should look something like this:

$router = Router::create($eventDispatcher, ['Your\\Controller\\Namespace'], [$dependency1, $dependency2]);
$router->route($request);

Your controllers should look something like this:

namespace Your\Controller\Namespace

class IndexController extends Croute\Controller
{
    public function __construct($dependency1, $dependency2)
    {
        //...
    }

    /**
     * Will be available at http://yourdomain/
     * and require the "required" (body or querystring) request parameter
     */
    public function indexAction($required, $optional = null)
    {
        echo 'Crouter Controller'; //you can echo or return a symfony Response
    }

    /**
     * Available at http://yourdomain/test
     */
    public function testAction()
    {
        return new Response('Test Action');
    }
}

The name of the controller determines which url it appears as:

It supports nested namespaces so that:

Annotations

Croute optionally supports controller and action annotations through the excellent minime/annotations library. To add an annotation handler simply:

$router->addAnnotationHandler($myhandler);

Two annotations are included (but must be added) out of the box @httpMethod and @secure.

@httpMethod

Restricts the allowed http methods. Returns a 400 response if the method does not match.

    /**
     * @httpMethod POST
     */
    public function saveAction()

@secure

Requires a secure connection. If the connection is not https send a 301 redirect to the same url with the https protocol.

/**
 * @secure
 */
class IndexController extends Controller
{

Events

Symfony events are dispatched for every step in the routing process. A total of 12 events are dispatched in a successful request:

  1. router.request
  2. router.controller_loaded
  3. router.controller_loaded.{ControllerName}
  4. router.before_action
  5. router.before_action.{ControllerName}
  6. router.before_action.{ControllerName}.{actionName}
  7. router.after_action
  8. router.after_action.{ControllerName}
  9. router.after_action.{ControllerName}.{actionName}
  10. router.before_response_sent
  11. router.response_sent
  12. router.response_sent.{ControllerName}
  13. router.response_sent.{ControllerName}.{actionName}

The {ControllerName} will be sans 'Controller' and {actionName} sans 'Action' i.e IndexController::indexAction -> router.before_action.Index.index.

At any time before the response is sent, in an event listener you can set a response on the event to bypass the action and send instead.

    public function myListener(ControllerLoadedEvent $event)
    {
        $event->setResponse(new Response('PermissionDenied', 403));
    }

Error Handling

Proper error handling is not really something that I can do for you. It's up to you to determine how to do logging, how and when to render a pretty error page. To handle errors, implement the EventHandlerInterface and set your error handler on the router. Your class will be called when common routing events occur (i.e. 404 errors) and when there is an exception during the routing process.

Contributing

Please see CONTRIBUTING for details.

You might also like...
klein.php is a fast & flexible router for PHP 5.3+

Klein.php klein.php is a fast & flexible router for PHP 5.3+ Flexible regular expression routing (inspired by Sinatra) A set of boilerplate methods fo

PHP Router class - A simple Rails inspired PHP router class.

PHP Router class A simple Rails inspired PHP router class. Usage of different HTTP Methods REST / Resourceful routing Reversed routing using named rou

Fast request router for PHP

FastRoute - Fast request router for PHP This library provides a fast implementation of a regular expression based router. Blog post explaining how the

Pux is a fast PHP Router and includes out-of-box controller tools

Pux Pux is a faster PHP router, it also includes out-of-box controller helpers. 2.0.x Branch Build Status (This branch is under development) Benchmark

A web router implementation for PHP.
A web router implementation for PHP.

Aura.Router Powerful, flexible web routing for PSR-7 requests. Installation and Autoloading This package is installable and PSR-4 autoloadable via Com

:bird: Simple PHP router

Macaw Macaw is a simple, open source PHP router. It's super small (~150 LOC), fast, and has some great annotated source code. This class allows you to

Toro is a PHP router for developing RESTful web applications and APIs.

Toro Toro is a PHP router for developing RESTful web applications and APIs. It is designed for minimalists who want to get work done. Quick Links Offi

A PHP rewrite of HackRouter by Facebook

Hack-Routing Fast, type-safe request routing, parameter retrieval, and link generation. It's a port of hack-router By Facebook, Inc. Components HTTP E

A lightweight and simple object oriented PHP Router

bramus/router A lightweight and simple object oriented PHP Router. Built by Bram(us) Van Damme (https://www.bram.us) and Contributors Features Support

Comments
  • Support routing http methods to actions

    Support routing http methods to actions

    via @httpMethodMap {"DELETE":"deleteAction"} annotation so that

    DELETE /example/ calls ExampleController::deleteAction()

    For better restful API building.

    Potentially have default map? DELETE -> deleteAction POST -> saveAction PUT -> saveAction

    enhancement 
    opened by thewunder 0
Owner
Michael O'Connell
Michael O'Connell
Routing - The Routing component maps an HTTP request to a set of configuration variables.

Routing Component The Routing component maps an HTTP request to a set of configuration variables. Getting Started $ composer require symfony/routing

Symfony 7.3k Jan 6, 2023
Fast PSR-7 based routing and dispatch component including PSR-15 middleware, built on top of FastRoute.

Route This package is compliant with PSR-1, PSR-2, PSR-4, PSR-7, PSR-11 and PSR-15. If you notice compliance oversights, please send a patch via pull

The League of Extraordinary Packages 608 Dec 30, 2022
Generate a PHP script for faster routing :rocket:

SwitchRoute Generating a PHP script for faster routing. The traditional way of routing uses regular expressions. This method was improved by FastRoute

Arnold Daniels 75 Nov 20, 2022
PHP routing (like laravel) (not complete yet)

PHP Router (under construction) This repository contains routing classes that enables you to define your routes similar to laravel 8 routes. Features

Kareem M. Fouad 6 Jan 16, 2022
Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.

The PHP HTTP Flight Router divineniiquaye/flight-routing is a HTTP router for PHP 7.1+ based on PSR-7 and PSR-15 with support for annotations, created

Divine Niiquaye Ibok 16 Nov 1, 2022
Ertuo: quick routing for PHP

Ertuo: quick routing for PHP Ertuo (anagram of "Route"), is a small PHP library that does routing better and faster than conventional regular expressi

Ertuo 29 Jul 19, 2022
PHPRouter is an easy-to-use, fast, and flexible PHP router package with express-style routing.

PHP-Router is a modern, fast, and adaptable composer package that provides express-style routing in PHP without a framework.

Ayodeji O. 4 Oct 20, 2022
🔍 This is a collection of utilities for routing and loading components.

Router Utilities - PHP Introduction A day will come when I will write documentation for this library. Until then, you can use this library to create r

Utilities for PHP 5 Sep 20, 2022
:tada: Release 2.0 is released! Very fast HTTP router for PHP 7.1+ (incl. PHP8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

HTTP router for PHP 7.1+ (incl. PHP 8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger) Installation compo

Sunrise // PHP 151 Jan 5, 2023
A Laravel package that introduces a clean object based alternative to Laravel route files.

Laravel Route Registrars This package introduces a clean object based way to define your routes in a Laravel application. A tutorial on the basic prem

Ollie Codes 22 Nov 25, 2022