Download the PHP package julienlinard/php-router without Composer
On this page you can find all versions of the php package julienlinard/php-router. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download julienlinard/php-router
More information about julienlinard/php-router
Files in julienlinard/php-router
Package php-router
Short Description Un routeur PHP moderne et complet avec support des routes dynamiques, middlewares, groupes de routes et génération d'URL. Compatible PHP 8+ avec Attributes.
License MIT
Homepage https://github.com/julien-lin/php-router
Informations about the package php-router
PHP Router
🇬🇧 Read in English
💝 Support the project
If this bundle is useful to you, consider becoming a sponsor to support the development and maintenance of this open source project.
A modern and complete PHP router for managing your application routes with support for dynamic routes, middlewares, and all essential features.
📋 Table of Contents
- Installation
- Quick Start
- Route Definition
- Dynamic Routes
- Route Groups
- URL Generation
- Request
- Response
- Middlewares
- Error Handling
- API Reference
- Complete Examples
🚀 Installation
Use Composer to install the package:
Requirements: PHP 8.0 or higher
⚡ Quick Start
🛣️ Route Definition
Routes are defined in your controllers using the Route attribute (PHP 8).
Simple Route
Routes with Multiple HTTP Methods
Route Registration
Route Groups
Route groups allow you to organize your routes with a common prefix and shared middlewares.
Complete Example:
🔄 Dynamic Routes
The router supports dynamic routes with parameters automatically extracted from the URL.
Route with One Parameter
Example URL: /user/123 → $userId = '123'
Route with Multiple Parameters
Example URL: /user/123/post/my-article → $userId = '123', $slug = 'my-article'
Accessing Parameters
📥 Request
The Request class provides complete access to HTTP request data.
Path and Method
Query Parameters
HTTP Headers
Cookies
Body (POST/PUT/PATCH)
Utility Methods
Customization for Tests
📤 Response
The Response class allows you to create and send HTTP responses.
Simple Response
JSON Response
Custom Headers
Available Methods
🔌 Dependency Injection
The Router now supports dependency injection via a Container. This allows automatic injection of dependencies into controllers and middlewares.
Configuration with Container
Controllers with Dependencies
Note: If no Container is set, the Router instantiates controllers directly with new.
🛡️ Middlewares
Middlewares allow you to execute code before request processing.
Important : The Middleware interface has been improved. The handle() method now returns ?Response instead of void. If a middleware returns a Response, execution stops and that response is returned. If it returns null, execution continues with the next middleware.
Global Middlewares
Route-Specific Middlewares
Available Middlewares
CorsMiddleware
AuthMiddleware
RoleMiddleware
LoggingMiddleware
Create a Custom Middleware
⚠️ Error Handling
The router automatically handles common errors:
- 404 Not Found: Route not found
- 405 Method Not Allowed: HTTP method not supported for this route
- 500 Internal Server Error: Server error (exceptions)
Customize Error Handling
📚 API Reference
Router
registerRoutes(string $controller): void
Registers all routes of a controller.
addMiddleware(Middleware $middleware): void
Adds a global middleware.
handle(Request $request): Response
Processes a request and returns the response.
getRoutes(): array
Returns all registered routes (debug).
getRouteByName(string $name): ?array
Returns a route by its name.
url(string $name, array $params = [], array $queryParams = []): ?string
Generates a URL from a route name and its parameters.
group(string $prefix, array $middlewares, callable $callback): void
Creates a route group with a prefix and common middlewares.
Request
Main Methods
getPath(): string- Request pathgetMethod(): string- HTTP methodgetQueryParams(): array- All query parametersgetQueryParam(string $key, $default = null)- A query parametergetHeaders(): array- All headersgetHeader(string $name, ?string $default = null): ?string- A headergetCookies(): array- All cookiesgetCookie(string $name, $default = null)- A cookiegetBody(): ?array- Parsed bodygetBodyParam(string $key, $default = null)- A body parametergetRawBody(): string- Raw bodygetRouteParams(): array- All route parametersgetRouteParam(string $key, $default = null)- A route parameterisAjax(): bool- Checks if it's an AJAX requestwantsJson(): bool- Checks if client accepts JSON
Response
Constructor
Static Methods
Response::json($data, int $statusCode = 200): self- Creates a JSON response
Instance Methods
setHeader(string $name, string $value): void- Sets a headersend(): void- Sends the HTTP responsegetStatusCode(): int- Status codegetContent(): string- ContentgetHeaders(): array- All headers
🔗 Integration with Other Packages
Integration with core-php
core-php automatically includes php-router. The router is accessible via Application::getRouter().
Integration with auth-php
Use authentication middlewares with php-router.
Standalone Usage
php-router can be used independently of all other packages.
🔗 URL Generation
The router allows you to generate URLs from route names, which facilitates maintenance and avoids hardcoded URLs.
Simple URL Generation
URL Generation with Query Parameters
Usage in Responses
Note: To use $router in your controllers, you can inject it via a dependency container or pass it as a parameter.
💡 Complete Examples
Example 1: Complete REST API with Groups
Example 2: Web Application with Authentication and Groups
🧪 Tests
The package includes a complete test suite. To run the tests:
📝 License
MIT License - See the LICENSE file for more details.
🤝 Contributing
Contributions are welcome! Feel free to open an issue or a pull request.
📧 Support
For any questions or issues, please open an issue on GitHub.
💝 Support the project
If this bundle is useful to you, consider becoming a sponsor to support the development and maintenance of this open source project.
Developed with ❤️ by Julien Linard