ice-cream/router

Ice Cream Router旨在成为世界上最简单的路由器。无烦恼,无困扰

1.0.3 2018-03-16 21:49 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:42:12 UTC


README

Build Status Packagist Made With Love

  • 需要PHP 7.2
  • 独立

这是一个非常轻量且非常基础的symfony路由概念包装。

其主要目标是尽可能简单易用,没有冗余或花哨的功能。

文档

为什么没有像其他Ice Cream包那样生成文档呢?

因为PHP Documentor有一个与symfony路由冲突的symfony配置。

如何使用它?

使用它的最简单方法是

use IceCreamRouter\Router;

$router = new Router();

$router->get('/foo/{id}', 'foo', function($id, $request, $response){
  return response->setContent('Id is: ' . $id);
});

$response = $router->processRoutes(Request::create('/foo/1', 'GET'));

var_dump($response->getContent()); // => Id is: 1

没有比这更简单的方法了。

同样的方式也适用于POSTPUTDELETE方法。这些方法与上面不同的地方是,闭包中不需要将$response作为变量。

use IceCreamRouter\Router;

$router = new Router();

$router->post('/foo/{id}', 'foo', function($id, $request){
  return new Response('the message passed in was: ' . $request->get('message') . ' and the id is: ' . $id);
});

$response = $router->processRoutes(Request::create('/foo/1', 'POST', ['message' => 'hello world']));

var_dump($response->getContent()); // => the message passed in was: hello world and the id is: 1

借助symfony的帮助,我们甚至足够智能,可以识别出具有不同方法的相同路由

use IceCreamRouter\Router;

$router = new Router();

$router->post('/foo/{id}', 'foo', function($id, $request){
  return new Response('the message passed in was: ' . $request->get('message') . ' and the id is: ' . $id);
});

$router->delete('/foo/{id}', 'foo_del', function($id, $request){
  return new Response('deleted');
});

$router->put('/foo/{id}', 'foo_put', function($id, $request){
  return new Response('the message put was: ' . $request->get('message') . ' and the id is: ' . $id);
});

$response = $router->processRoutes(Request::create('/foo/1', 'POST', ['message' => 'hello world']));

var_dump($response->getContent()); // => the message passed in was: hello world and the id is: 1

在这里,您可以看到我们有相同的终点,但使用了不同的方法。因此,我们可以创建一个只做POST请求的请求,它将匹配正确的终点。