Convert Figma logo to code with AI

dannyvankooten logoAltoRouter

PHP routing class. Lightweight yet flexible. Supports REST, dynamic and reversed routing.

1,219
230
1,219
30

Top Related Projects

Fast request router for PHP

7,569

Maps an HTTP request to a set of configuration variables

1,080

A lightweight and simple object oriented PHP Router

A fast & flexible router

Quick Overview

AltoRouter is a lightweight PHP routing class that provides a simple and flexible way to map URLs to callback functions or controller actions. It supports dynamic route patterns, custom regular expressions, and reverse routing, making it easy to create clean and SEO-friendly URLs for web applications.

Pros

  • Lightweight and fast, with minimal overhead
  • Easy to integrate into existing PHP projects
  • Supports dynamic route patterns and custom regular expressions
  • Includes reverse routing functionality for generating URLs

Cons

  • Limited built-in middleware support
  • No built-in dependency injection container
  • May require additional setup for more complex routing scenarios
  • Not actively maintained (last commit was in 2021)

Code Examples

  1. Basic routing:
$router = new AltoRouter();
$router->map('GET', '/users', function() {
    echo 'Users List';
});
$router->map('GET', '/users/[i:id]', function($id) {
    echo "User: $id";
});
  1. Using controllers and methods:
$router->map('GET', '/blog', 'BlogController#index');
$router->map('GET', '/blog/[i:id]', 'BlogController#show');
  1. Reverse routing:
$router->map('GET', '/users/[i:id]/edit', 'UserController#edit', 'user_edit');
$url = $router->generate('user_edit', ['id' => 5]);
// Output: /users/5/edit

Getting Started

  1. Install AltoRouter using Composer:
composer require altorouter/altorouter
  1. Create a new PHP file (e.g., index.php) and add the following code:
<?php
require 'vendor/autoload.php';

$router = new AltoRouter();

// Map your routes
$router->map('GET', '/', function() {
    echo 'Hello, World!';
});

// Match the current request
$match = $router->match();

// Call the matched method
if ($match && is_callable($match['target'])) {
    call_user_func_array($match['target'], $match['params']);
} else {
    // Handle 404
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
    echo '404 Not Found';
}
  1. Configure your web server to route all requests to index.php.

Competitor Comparisons

Fast request router for PHP

Pros of FastRoute

  • Higher performance and faster routing due to its optimized algorithm
  • Supports more advanced routing patterns, including optional parameters and wildcards
  • Smaller memory footprint, especially for large route sets

Cons of FastRoute

  • Less intuitive API, requiring more setup and configuration
  • Limited built-in features compared to AltoRouter's more comprehensive offering
  • Steeper learning curve for beginners

Code Comparison

AltoRouter:

$router = new AltoRouter();
$router->map('GET', '/users/[i:id]', 'UserController#show');
$match = $router->match();

FastRoute:

$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/users/{id:\d+}', 'UserController#show');
});
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);

Both libraries offer PHP routing solutions, but FastRoute focuses on performance optimization at the cost of simplicity, while AltoRouter provides a more user-friendly approach with additional features out of the box. The choice between them depends on project requirements, performance needs, and developer preferences.

7,569

Maps an HTTP request to a set of configuration variables

Pros of Symfony Routing

  • More feature-rich and flexible, supporting advanced routing scenarios
  • Part of a larger, well-established framework with extensive documentation
  • Better integration with other Symfony components

Cons of Symfony Routing

  • Steeper learning curve due to more complex API
  • Heavier and may be overkill for simple projects
  • Requires more setup and configuration

Code Comparison

AltoRouter:

$router = new AltoRouter();
$router->map('GET', '/users/[i:id]', 'UserController#show');
$match = $router->match();

Symfony Routing:

$routes = new RouteCollection();
$routes->add('user_show', new Route('/users/{id}', [
    '_controller' => 'UserController::show',
]));
$matcher = new UrlMatcher($routes, new RequestContext());
$parameters = $matcher->match('/users/1');

Both libraries provide routing functionality, but Symfony Routing offers more advanced features at the cost of complexity. AltoRouter is simpler and more lightweight, making it suitable for smaller projects or those requiring minimal routing. Symfony Routing is better suited for larger applications or those already using the Symfony framework.

1,080

A lightweight and simple object oriented PHP Router

Pros of Router

  • More active development and maintenance
  • Supports PHP 8.0 and above
  • Offers middleware support out of the box

Cons of Router

  • Less extensive documentation compared to AltoRouter
  • Fewer stars and community adoption on GitHub

Code Comparison

Router:

$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)', function($name) {
    echo 'Hello ' . htmlentities($name);
});
$router->run();

AltoRouter:

$router = new AltoRouter();
$router->map('GET', '/hello/[*:name]', function($name) {
    echo 'Hello ' . htmlentities($name);
});
$match = $router->match();

Both routers offer similar functionality for defining routes and handling requests. Router uses a more modern approach with method chaining and a dedicated run() method, while AltoRouter separates route definition and matching.

Router provides a cleaner syntax for defining routes and supports more recent PHP versions. However, AltoRouter has been around longer and has more extensive documentation, which can be beneficial for beginners or larger projects requiring detailed guidance.

The choice between these routers depends on specific project requirements, PHP version compatibility, and personal preference for syntax and features.

A fast & flexible router

Pros of klein.php

  • More feature-rich, offering middleware support and dependency injection
  • Provides built-in HTTP caching mechanisms
  • Includes a service container for better organization of application components

Cons of klein.php

  • Slightly more complex to set up and use compared to AltoRouter
  • May have a steeper learning curve for beginners
  • Larger codebase, which could impact performance in very small projects

Code Comparison

klein.php:

$klein = new \Klein\Klein();

$klein->respond('GET', '/users/[i:id]', function ($request, $response, $service) {
    $userId = $request->id;
    // Handle user retrieval
});

$klein->dispatch();

AltoRouter:

$router = new AltoRouter();

$router->map('GET', '/users/[i:id]', function($id) {
    // Handle user retrieval
});

$match = $router->match();

Both routers offer similar basic routing capabilities, but klein.php provides more built-in features and a slightly different syntax. AltoRouter focuses on simplicity and lightweight implementation, while klein.php offers a more comprehensive framework-like approach with additional features like middleware and service containers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

AltoRouter PHP status Latest Stable Version License

AltoRouter is a small but powerful routing class, heavily inspired by klein.php.

$router = new AltoRouter();

// map homepage
$router->map('GET', '/', function() {
    require __DIR__ . '/views/home.php';
});

// dynamic named route
$router->map('GET|POST', '/users/[i:id]/', function($id) {
  $user = .....
  require __DIR__ . '/views/user/details.php';
}, 'user-details');

// echo URL to user-details page for ID 5
echo $router->generate('user-details', ['id' => 5]); // Output: "/users/5"

Features

  • Can be used with all HTTP Methods
  • Dynamic routing with named route parameters
  • Reversed routing
  • Flexible regular expression routing (inspired by Sinatra)
  • Custom regexes

Getting started

You need PHP >= 7.3 to use AltoRouter, although we highly recommend you use an officially supported PHP version that is not EOL.

Contributors

License

MIT License

Copyright (c) 2012 Danny van Kooten hi@dannyvankooten.com

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.