Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 068e05a

Browse files
Added Where Constraints and Improved Documentation
1 parent 4aeaf91 commit 068e05a

File tree

9 files changed

+1282
-4040
lines changed

9 files changed

+1282
-4040
lines changed

‎README.md

Lines changed: 274 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1-
# A simple Router for PHP App using PSR-7 message implementation
1+
# PHP Router : A versatile and efficient PHP routing solution designed to streamline route management within PHP applications.
22

33
[![Latest Stable Version](http://poser.pugx.org/devcoder-xyz/php-router/v)](https://packagist.org/packages/devcoder-xyz/php-router) [![Total Downloads](http://poser.pugx.org/devcoder-xyz/php-router/downloads)](https://packagist.org/packages/devcoder-xyz/php-router) [![Latest Unstable Version](http://poser.pugx.org/devcoder-xyz/php-router/v/unstable)](https://packagist.org/packages/devcoder-xyz/php-router) [![License](http://poser.pugx.org/devcoder-xyz/php-router/license)](https://packagist.org/packages/devcoder-xyz/php-router) [![PHP Version Require](http://poser.pugx.org/devcoder-xyz/php-router/require/php)](https://packagist.org/packages/devcoder-xyz/php-router)
44

5+
## Description
6+
7+
PHP Router is a simple and efficient routing library designed for PHP applications. It provides a straightforward way to define routes, handle HTTP requests, and generate URLs. Built with PSR-7 message implementation in mind, it seamlessly integrates with PHP applications.
8+
9+
510
## Installation
611

7-
Use [Composer](https://getcomposer.org/)
12+
You can install PHP Router via Composer. Just run:
813

914
### Composer Require
1015
```
@@ -13,13 +18,24 @@ composer require devcoder-xyz/php-router
1318

1419
## Requirements
1520

16-
* PHP version 7.4
21+
* PHP version 7.4 or above
1722
* Enable URL rewriting on your web server
18-
* Optional : Need package for PSR-7 HTTP Message
19-
(example : guzzlehttp/psr7 )
23+
* Optional: PSR-7 HTTP Message package (e.g., guzzlehttp/psr7)
24+
25+
## Usage
26+
27+
1. **Define Routes**: Define routes using the `Route` class provided by PHP Router.
28+
29+
2. **Initialize Router**: Initialize the `Router` class with the defined routes.
30+
31+
3. **Match Requests**: Match incoming HTTP requests to defined routes.
32+
33+
4. **Handle Requests**: Handle matched routes by executing appropriate controllers or handlers.
34+
35+
5. **Generate URLs**: Generate URLs for named routes.
2036

21-
**How to use ?**
2237

38+
## Example
2339
```php
2440
<?php
2541
class IndexController {
@@ -60,41 +76,34 @@ class ArticleController {
6076
return json_encode(['id' => 4]);
6177
}
6278
}
79+
```
6380

81+
```php
82+
// Define your routes
6483
$routes = [
6584
new \DevCoder\Route('home_page', '/', [IndexController::class]),
6685
new \DevCoder\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']),
6786
new \DevCoder\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']),
6887
];
69-
$router = new \DevCoder\Router($routes, 'http://localhost');
70-
```
7188

72-
## Example
89+
// Initialize the router
90+
$router = new \DevCoder\Router($routes, 'http://localhost');
7391

74-
```php
7592
try {
76-
// Example
77-
78-
// \Psr\Http\Message\ServerRequestInterface
93+
// Match incoming request
7994
$route = $router->match(ServerRequestFactory::fromGlobals());
80-
// OR
8195

82-
// $_SERVER['REQUEST_URI'] = '/api/articles/2'
83-
// $_SERVER['REQUEST_METHOD'] = 'GET'
84-
$route = $router->matchFromPath($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
85-
96+
// Handle the matched route
8697
$handler = $route->getHandler();
87-
// $attributes = ['id' => 2]
8898
$attributes = $route->getAttributes();
89-
9099
$controllerName = $handler[0];
91100
$methodName = $handler[1] ?? null;
92-
93101
$controller = new $controllerName();
102+
103+
// Invoke the controller method
94104
if (!is_callable($controller)) {
95105
$controller = [$controller, $methodName];
96106
}
97-
98107
echo $controller(...array_values($attributes));
99108

100109
} catch (\DevCoder\Exception\MethodNotAllowed $exception) {
@@ -105,27 +114,255 @@ try {
105114
exit();
106115
}
107116
```
108-
How to Define Route methods
117+
118+
## Features
119+
120+
- Lightweight and easy-to-use
121+
- Supports HTTP method-based routing
122+
- Flexible route definition with attribute constraints
123+
- Exception handling for method not allowed and route not found scenarios
124+
125+
## Route Definition
126+
127+
Routes can be defined using the `Route` class provided by PHP Router. You can specify HTTP methods, attribute constraints, and handler methods for each route.
128+
109129
```php
110130
$route = new \DevCoder\Route('api_articles_post', '/api/articles', [ArticleController::class, 'post'], ['POST']);
111131
$route = new \DevCoder\Route('api_articles_put', '/api/articles/{id}', [ArticleController::class, 'put'], ['PUT']);
132+
```
133+
### Easier Route Definition with Static Methods
134+
135+
To make route definition even simpler and more intuitive, the `RouteTrait` provides static methods for creating different types of HTTP routes. Here's how to use them:
136+
137+
#### Method `get()`
138+
139+
```php
112140
/**
113-
* ---- OR -----
114-
*/
115-
$route = \DevCoder\Route::post('api_articles_post', '/api/articles', [ArticleController::class, 'post']);
116-
$route = \DevCoder\Route::put('api_articles_put', '/api/articles/{id}', [ArticleController::class, 'put']);
141+
* Creates a new GET route with the given name, path, and handler.
142+
*
143+
* @param string $name The name of the route.
144+
* @param string $path The path of the route.
145+
* @param mixed $handler The handler for the route.
146+
* @return BaseRoute The newly created GET route.
147+
*/
148+
public static function get(string $name, string $path, $handler): BaseRoute
149+
{
150+
return new BaseRoute($name, $path, $handler);
151+
}
152+
```
153+
154+
Example Usage:
155+
156+
```php
157+
$route = Route::get('home', '/', [HomeController::class, 'index']);
158+
```
159+
160+
#### Method `post()`
161+
162+
```php
163+
/**
164+
* Creates a new POST route with the given name, path, and handler.
165+
*
166+
* @param string $name The name of the route.
167+
* @param string $path The path of the route.
168+
* @param mixed $handler The handler for the route.
169+
* @return BaseRoute The newly created POST route.
170+
*/
171+
public static function post(string $name, string $path, $handler): BaseRoute
172+
{
173+
return new BaseRoute($name, $path, $handler, ['POST']);
174+
}
175+
```
176+
177+
Example Usage:
178+
179+
```php
180+
$route = Route::post('submit_form', '/submit', [FormController::class, 'submit']);
181+
```
182+
183+
#### Method `put()`
184+
185+
```php
186+
/**
187+
* Creates a new PUT route with the given name, path, and handler.
188+
*
189+
* @param string $name The name of the route.
190+
* @param string $path The path of the route.
191+
* @param mixed $handler The handler for the route.
192+
* @return BaseRoute The newly created PUT route.
193+
*/
194+
public static function put(string $name, string $path, $handler): BaseRoute
195+
{
196+
return new BaseRoute($name, $path, $handler, ['PUT']);
197+
}
198+
```
199+
200+
Example Usage:
201+
202+
```php
203+
$route = Route::put('update_item', '/item/{id}', [ItemController::class, 'update']);
117204
```
118-
Generating URLs
205+
206+
#### Method `delete()`
207+
119208
```php
120-
echo $router->generateUri('home_page');
121-
// /
122-
echo $router->generateUri('api_articles', ['id' => 1]);
123-
// /api/articles/1
209+
/**
210+
* Creates a new DELETE route with the given name, path, and handler.
211+
*
212+
* @param string $name The name of the route.
213+
* @param string $path The path of the route.
214+
* @param mixed $handler The handler for the route.
215+
* @return BaseRoute The newly created DELETE route.
216+
*/
217+
public static function delete(string $name, string $path, $handler): BaseRoute
218+
{
219+
return new BaseRoute($name, $path, $handler, ['DELETE']);
220+
}
221+
```
124222

125-
echo $router->generateUri('api_articles', ['id' => 1], true);
126-
// http://localhost/api/articles/1
223+
Example Usage:
224+
225+
```php
226+
$route = Route::delete('delete_item', '/item/{id}', [ItemController::class, 'delete']);
227+
```
228+
229+
With these static methods, defining routes becomes a breeze, providing a smoother and more efficient way to handle routing in your PHP application.
230+
231+
### Using `where` Constraints in the Route Object
232+
233+
The `Route` object allows you to define constraints on route parameters using the `where` methods. These constraints validate and filter parameter values based on regular expressions. Here's how to use them:
234+
235+
#### Method `whereNumber()`
236+
237+
This method applies a numeric constraint to the specified route parameters.
238+
239+
```php
240+
/**
241+
* Sets a number constraint on the specified route parameters.
242+
*
243+
* @param mixed ...$parameters The route parameters to apply the constraint to.
244+
* @return self The updated Route instance.
245+
*/
246+
public function whereNumber(...$parameters): self
247+
{
248+
$this->assignExprToParameters($parameters, '[0-9]+');
249+
return $this;
250+
}
251+
```
252+
253+
Example Usage:
254+
255+
```php
256+
$route = (new Route('example', '/example/{id}'))->whereNumber('id');
257+
```
258+
259+
#### Method `whereSlug()`
260+
261+
This method applies a slug constraint to the specified route parameters, allowing alphanumeric characters and hyphens.
262+
263+
```php
264+
/**
265+
* Sets a slug constraint on the specified route parameters.
266+
*
267+
* @param mixed ...$parameters The route parameters to apply the constraint to.
268+
* @return self The updated Route instance.
269+
*/
270+
public function whereSlug(...$parameters): self
271+
{
272+
$this->assignExprToParameters($parameters, '[a-z0-9-]+');
273+
return $this;
274+
}
275+
```
276+
277+
Example Usage:
278+
279+
```php
280+
$route = (new Route('article', '/article/{slug}'))->whereSlug('slug');
281+
```
282+
283+
#### Method `whereAlphaNumeric()`
284+
285+
This method applies an alphanumeric constraint to the specified route parameters.
286+
287+
```php
288+
/**
289+
* Sets an alphanumeric constraint on the specified route parameters.
290+
*
291+
* @param mixed ...$parameters The route parameters to apply the constraint to.
292+
* @return self The updated Route instance.
293+
*/
294+
public function whereAlphaNumeric(...$parameters): self
295+
{
296+
$this->assignExprToParameters($parameters, '[a-zA-Z0-9]+');
297+
return $this;
298+
}
299+
```
300+
301+
Example Usage:
302+
303+
```php
304+
$route = (new Route('user', '/user/{username}'))->whereAlphaNumeric('username');
305+
```
306+
307+
#### Method `whereAlpha()`
308+
309+
This method applies an alphabetic constraint to the specified route parameters.
310+
311+
```php
312+
/**
313+
* Sets an alphabetic constraint on the specified route parameters.
314+
*
315+
* @param mixed ...$parameters The route parameters to apply the constraint to.
316+
* @return self The updated Route instance.
317+
*/
318+
public function whereAlpha(...$parameters): self
319+
{
320+
$this->assignExprToParameters($parameters, '[a-zA-Z]+');
321+
return $this;
322+
}
323+
```
324+
325+
Example Usage:
326+
327+
```php
328+
$route = (new Route('category', '/category/{name}'))->whereAlpha('name');
329+
```
330+
331+
#### Method `where()`
332+
333+
This method allows you to define a custom constraint on a specified route parameter.
334+
335+
```php
336+
/**
337+
* Sets a custom constraint on the specified route parameter.
338+
*
339+
* @param string $parameter The route parameter to apply the constraint to.
340+
* @param string $expression The regular expression constraint.
341+
* @return self The updated Route instance.
342+
*/
343+
public function where(string $parameter, string $expression): self
344+
{
345+
$this->wheres[$parameter] = $expression;
346+
return $this;
347+
}
348+
```
349+
350+
Example Usage:
351+
352+
```php
353+
$route = (new Route('product', '/product/{code}'))->where('code', '\d{4}');
354+
```
355+
356+
By using these `where` methods, you can apply precise constraints on your route parameters, ensuring proper validation of input values.
357+
358+
## Generating URLs
359+
360+
Generate URLs for named routes using the `generateUri` method.
361+
362+
```php
363+
echo $router->generateUri('home_page'); // /
364+
echo $router->generateUri('api_articles', ['id' => 1]); // /api/articles/1
365+
echo $router->generateUri('api_articles', ['id' => 1], true); // http://localhost/api/articles/1
127366
```
128367

129-
Ideal for small project.
130-
Simple and easy!
131-
[https://github.com/devcoder-xyz/php-router](https://github.com/devcoder-xyz/php-router)
368+
Ideal for small to medium-sized projects, PHP Router offers simplicity and efficiency in handling routing tasks for PHP applications.

‎composer.json

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "devcoder-xyz/php-router",
3-
"description": "Simple and fast php router",
3+
"description": "A versatile and efficient PHP routing solution designed to streamline route management within PHP applications.",
44
"type": "package",
55
"autoload": {
66
"psr-4": {
@@ -22,8 +22,7 @@
2222
"psr/http-factory": "^1.0"
2323
},
2424
"require-dev": {
25-
"phpunit/phpunit": "^9.5",
26-
"nunomaduro/phpinsights": "^2.6"
25+
"phpunit/phpunit": "^9.5"
2726
},
2827
"config": {
2928
"allow-plugins": {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /