Skip to content

Commit dda609c

Browse files
committed
add examples
1 parent 70f29f6 commit dda609c

File tree

27 files changed

+559
-258
lines changed

27 files changed

+559
-258
lines changed

README.md

Lines changed: 81 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ After configurations above, you can start using PhpRouter in your entry point (`
4949

5050
```php
5151
use MiladRahimi\PhpRouter\Router;
52-
use Zend\Diactoros\Response\HtmlResponse;
5352
use Zend\Diactoros\Response\JsonResponse;
5453

5554
$router = new Router();
@@ -63,7 +62,7 @@ $router->post('/blog/post/{id}', function ($id) {
6362
});
6463

6564
$router->patch('/json', function () {
66-
return JsonResponse(['message' => 'This is a JSON response!']);
65+
return new JsonResponse(["message" => "posted data to user: $id"]);
6766
});
6867

6968
$router->dispatch();
@@ -99,7 +98,7 @@ $router
9998
->dispatch();
10099
```
101100

102-
You may want to use your custom http methods so take look at this example:
101+
You may want to use your custom http methods, so take look at this example:
103102

104103
```php
105104
use MiladRahimi\PhpRouter\Router;
@@ -142,19 +141,14 @@ use MiladRahimi\PhpRouter\Router;
142141

143142
$router = new Router();
144143

145-
$router->get('/1', function () {
144+
$router->get('/closure', function () {
146145
return 'Closure as a controller';
147146
});
148147

149-
$closure = function() {
150-
return 'Stored closure as a controller';
151-
};
152-
$router->get('/2', $closure);
153-
154148
function func() {
155149
return 'Function as a controller';
156150
}
157-
$router->get('/3', 'func');
151+
$router->get('/function', 'func');
158152

159153
$router->dispatch();
160154
```
@@ -175,7 +169,7 @@ class Controller
175169
}
176170
}
177171

178-
$router->get('/4', 'Controller@method');
172+
$router->get('/method', 'Controller@method');
179173

180174
$router->dispatch();
181175
```
@@ -188,22 +182,22 @@ use MiladRahimi\PhpRouter\Router;
188182

189183
$router = new Router();
190184

191-
$router->get('/5', 'App\Controllers\TheController@method');
185+
$router->get('/ns', 'App\Controllers\TheController@show');
192186
// OR
193-
$router->get('/5', TheController::class . '@method');
187+
$router->get('/ns', TheController::class . '@show');
194188

195189
$router->dispatch();
196190
```
197191

198-
Or you can pass the namespace to the Router instance and only write the controller name in the routes this way:
192+
Or you can pass the namespace to the Router constructor and only write the controller name in the routes this way:
199193

200194
```php
201195
use MiladRahimi\PhpRouter\Router;
202196

203197
$router = new Router('', 'App\Controllers');
204198

205-
$router->get('/5', 'TheController@method');
206-
// PhpRouter looks for App\Controllers\TheController@method
199+
$router->get('/', 'TheController@show');
200+
// PhpRouter looks for App\Controllers\TheController@show
207201

208202
$router->dispatch();
209203
```
@@ -218,54 +212,52 @@ use MiladRahimi\PhpRouter\Router;
218212
$router = new Router();
219213

220214
// Required parameter
221-
$router->get('/blog/post/{id}', function ($id) {
222-
return 'Content of the post: ' . $id;
215+
$router->get('/post/{id}', function ($id) {
216+
return "The content of post $id";
223217
});
224218

225219
// Optional parameter
226-
$router->get('/path/to/{info?}', function ($info = null) {
227-
return 'Info may be present or may be NULL.';
220+
$router->get('/welcome/{name?}', function ($name = null) {
221+
return 'Welcome ' . ($name ?: 'Dear User');
228222
});
229223

230224
// Optional parameter, Optional Slash!
231-
$router->get('/path/to/?{info?}', function ($info = null) {
232-
return 'info may be present or may be NULL.';
225+
$router->get('/profile/?{user?}', function ($user = null) {
226+
return ($user ?: 'Your') . ' profile';
233227
});
234228

235229
// Optional parameter with default value
236-
$router->get('/path/to/{info?}', function ($info = 'Default') {
237-
return 'info may be present or may be Default.';
230+
$router->get('/role/{role?}', function ($role = 'admin') {
231+
return "Role is $role";
232+
});
233+
234+
// Multiple parameters
235+
$router->get('/post/{pid}/comment/{cid}', function ($pid, $cid) {
236+
return "The comment $cid of the post $pid";
238237
});
239238

240239
$router->dispatch();
241240
```
242241

243-
In default, route parameters can match any value, but you can define a regular expression for them and it applys to all of them in all the routes.
242+
In default, a route parameter can match any value, but you can define a regular expression pattern for it.
244243

245244
```php
246245
use MiladRahimi\PhpRouter\Router;
247246

248-
class BlogController
249-
{
250-
function getPost(int $id)
251-
{
252-
return 'Content of the post: ' . $id;
253-
}
254-
}
255-
256247
$router = new Router();
257248

258-
// ID must be a numeric value
259249
$router->define('id', '[0-9]+');
260250

261-
$router->get('/blog/post/{id}', 'BlogController@getPost');
251+
$router->get('/blog/post/{id}', function (int $id) {
252+
return 'Content of the post: ' . $id;
253+
});
262254

263255
$router->dispatch();
264256
```
265257

266258
## HTTP Request and Request
267259

268-
PhpRouter uses [zend-diactoros](https://github.com/zendframework/zend-diactoros) package (version 2) to provide [PSR-7](https://www.php-fig.org/psr/psr-7) complaint request and response objects to your controllers and middleware.
260+
PhpRouter uses [zend-diactoros](https://github.com/zendframework/zend-diactoros) package (v2) to provide [PSR-7](https://www.php-fig.org/psr/psr-7) complaint request and response objects to your controllers and middleware.
269261

270262
### Request
271263

@@ -291,8 +283,8 @@ $router->get('/', function (ServerRequest $request) {
291283
]);
292284
});
293285

294-
$router->post('/blog/posts', function (ServerRequest $request) {
295-
$post = new \App\Models\Post();
286+
$router->post('/posts', function (ServerRequest $request) {
287+
$post = new PostModel();
296288
$post->title = $request->getQueryParams()['title'];
297289
$post->content = $request->getQueryParams()['content'];
298290
$post->save();
@@ -324,7 +316,7 @@ $router
324316
return new HtmlResponse('<html>This is also an HTML response</html>', 200);
325317
})
326318
->get('/json', function () {
327-
return new JsonResponse(['message' => 'Unauthorized!'], 401);
319+
return new JsonResponse(['error' => 'Unauthorized!'], 401);
328320
})
329321
->get('/text', function () {
330322
return new TextResponse('This is a plain text...');
@@ -334,7 +326,6 @@ $router
334326
});
335327

336328
$router->dispatch();
337-
338329
```
339330

340331
#### Redirection Response
@@ -380,7 +371,7 @@ interface Middleware
380371
*
381372
* @param ServerRequestInterface $request
382373
* @param Closure $next
383-
* @return ResponseInterface|mixed
374+
* @return ResponseInterface|mixed|null
384375
*/
385376
public function handle(ServerRequestInterface $request, Closure $next);
386377
}
@@ -394,8 +385,8 @@ it passes the request to the next middleware or the controller (if there is no m
394385
```php
395386
use MiladRahimi\PhpRouter\Router;
396387
use MiladRahimi\PhpRouter\Middleware;
397-
use Psr\Http\Message\ResponseInterface;
398388
use Psr\Http\Message\ServerRequestInterface;
389+
use Zend\Diactoros\Response\JsonResponse;
399390

400391
class AuthMiddleware implements Middleware
401392
{
@@ -405,22 +396,24 @@ class AuthMiddleware implements Middleware
405396
return $next($request);
406397
}
407398

408-
return new EmptyResponse(401);
399+
return new JsonResponse(['error' => 'Unauthorized!'], 401);
409400
}
410401
}
411402

412403
$router = new Router();
413404

414-
$router->get('/auth', function () { return 'OK' }, AuthMiddleware::class);
405+
$router->get('/admin', function () {
406+
return 'This is admin panel!';
407+
}, AuthMiddleware::class);
415408

416409
$router->dispatch();
417410
```
418411

419412
Middleware can be implemented using closures but it doesn’t make scense to do so!
420413

421-
## Domain and Subdomain
414+
## Domain and Sub-domain
422415

423-
Your application may serve different services on different domains/subdomains or it may assign subdomain dynamically to users or services. In this case, you need to specify domain or subdomain in addition to the URIs in your routes.
416+
Your application may serve different services on different domains/subdomains or it may assign sub-domain dynamically to users or services. In this case, you need to specify domain or sub-domain in addition to the URIs in your routes.
424417

425418
```php
426419
use MiladRahimi\PhpRouter\Router;
@@ -430,44 +423,50 @@ $router = new Router();
430423
// Domain
431424
$router->get('/', 'Controller@method', [], 'domain2.com');
432425

433-
// Subdomain
426+
// Sub-domain
434427
$router->get('/', 'Controller@method', [], 'server2.domain.com');
435428

436-
// Subdomain regex pattern
429+
// Sub-domain with regex pattern
437430
$router->get('/', 'Controller@method', [], '(.*).domain.com');
438431

439432
$router->dispatch();
440433
```
441434

442-
Notice that domain parameter receives a regex pattern not a simple string.
443-
444435
## Route Groups
445436

446-
Usually routes can fit in a groups that have common attributes like middleware, domain/subdomain and prefix. To group routes you can follow the example below.
437+
Usually routes can fit in a groups that have common attributes like middleware, domain/sub-domain and prefix. To group routes you can follow the example below.
447438

448439
```php
440+
use MiladRahimi\PhpRouter\Examples\Samples\SimpleMiddleware;
449441
use MiladRahimi\PhpRouter\Router;
450442

451443
$router = new Router();
452444

445+
// A group with uri prefix
453446
$router->group(['prefix' => '/admin'], function (Router $router) {
454-
// URI: /admin/setting
455-
$router->get('/setting', 'AdminController@getSetting');
447+
// URI: /admin/setting
448+
$router->get('/setting', function () {
449+
return 'Setting.';
450+
});
456451
});
457452

453+
// All of group properties together!
458454
$attributes = [
459-
'prefix' => '/products',
460-
'namespace' => 'App\Controllers',
461-
'domain' => 'shop.example.com',
462-
'middleware' => SampleMiddleware::class,
455+
'prefix' => '/products',
456+
'namespace' => 'App\Controllers',
457+
'domain' => 'shop.example.com',
458+
'middleware' => SimpleMiddleware::class,
463459
];
464460

461+
// A group with many common properties!
465462
$router->group($attributes, function (Router $router) {
466463
// URI: http://shop.example.com/products/{id}
467464
// Controller: App\Controllers\ShopController@getProduct
468465
// Domain: shop.example.com
469466
// Middleware: SampleMiddleware
470-
$router->get('/{id}', 'ShopController@getProduct');
467+
$router->get('/{id}', function ($id) {
468+
return 'Wow.';
469+
});
471470
});
472471

473472
$router->dispatch();
@@ -485,10 +484,14 @@ use MiladRahimi\PhpRouter\Router;
485484
$router = new Router('/shop');
486485

487486
// URI: /shop/about
488-
$router->get('/about', 'ShopController@getAbout');
487+
$router->get('/about', function () {
488+
return 'About the shop.';
489+
});
489490

490491
// URI: /shop/product/{id}
491-
$router->get('/product/{id}', 'ShopController@getProduct');
492+
$router->get('/product/{id}', function ($id) {
493+
return 'A product.';
494+
});
492495

493496
$router->dispatch();
494497
```
@@ -503,20 +506,18 @@ use Zend\Diactoros\Response\JsonResponse;
503506
$router = new Router();
504507

505508
$router->name('about')->get('/about', function () {
506-
return 'About me!'
507-
});
508-
$router->name('help')->get('/help', function () {
509-
return 'Help me!'
509+
return 'About.';
510510
});
511-
$router->name('page')->get('/page/{id}', function ($id) {
512-
return 'Content of the page: ' . $id;
511+
$router->name('post')->get('/post/{id}', function ($id) {
512+
return 'Content of the post: ' . $id;
513513
});
514514
$router->name('home')->get('/', function (Router $router) {
515515
return new JsonResponse([
516-
"link_about" => $router->url('about'), /* /about */
517-
"link_help" => $router->url('help') /* /help */
518-
"link_page_1" => $router->url('page', ['id' => 1]), /* /page/1 */
519-
"link_page_2" => $router->url('page', ['id' => 2]) /* /page/2 */
516+
'links' => [
517+
'about' => $router->url('about'), /* Result: /about */
518+
'post1' => $router->url('post', ['id' => 1]), /* Result: /post/1 */
519+
'post2' => $router->url('post', ['id' => 2]) /* Result: /post/2 */
520+
]
520521
]);
521522
});
522523

@@ -534,11 +535,11 @@ use Zend\Diactoros\Response\JsonResponse;
534535
$router = new Router();
535536

536537
$router->name('home')->get('/', function (Router $router) {
537-
return JsonResponse([
538-
"current_page_name" => $router->currentRoute()->getName() /* home */
539-
"current_page_uri" => $router->currentRoute()->getUri() /* /home */
540-
"current_page_method" => $router->currentRoute()->getMethod() /* GET */
541-
"current_page_domain" => $router->currentRoute()->getDomain() /* NULL */
538+
return new JsonResponse([
539+
'current_page_name' => $router->currentRoute()->getName(), /* Result: home */
540+
'current_page_uri' => $router->currentRoute()->getUri(), /* Result: / */
541+
'current_page_method' => $router->currentRoute()->getMethod(), /* Result: GET */
542+
'current_page_domain' => $router->currentRoute()->getDomain(), /* Result: null */
542543
]);
543544
});
544545

@@ -552,19 +553,21 @@ Your application runs through the `Router::disptach()` method, you should put it
552553
```php
553554
use MiladRahimi\PhpRouter\Router;
554555
use MiladRahimi\PhpRouter\Exceptions\RouteNotFoundException;
556+
use Zend\Diactoros\Response\HtmlResponse;
555557

556558
$router = new Router();
557559

558560
$router->get('/', function () {
559-
return 'This is home page!';
561+
return 'Home.';
560562
});
561563

562564
try {
563565
$router->dispatch();
564566
} catch (RouteNotFoundException $e) {
565-
$router->getPublisher()->publish(new EmptyResponse(404));
567+
$router->getPublisher()->publish(new HtmlResponse('Not found.', 404));
566568
} catch (Throwable $e) {
567-
// other exceptions...
569+
// Log and report...
570+
$router->getPublisher()->publish(new HtmlResponse('Internal error.', 500));
568571
}
569572
```
570573

0 commit comments

Comments
 (0)