title: routing meta:

  • name: description content: easyswoole,routing,Swoole routing component,swoole api,Swoole custom routing,restful
  • name: keywords content: swoole|swoole extension|swoole framework|easyswoole|routing|Swoole routing component|swoole api|Swoole custom routing|restful

Custom routing

::: warning Reference Demo: Router.php :::

EasySwoole supports custom routing, and its routing is implemented by [fastRoute] (https://github.com/nikic/FastRoute), so its routing rules are consistent with it. For detailed documentation of this component, please refer to [GitHub documentation] (https://github.com/nikic/FastRoute/blob/master/README.md)

Sample Code:

Create a new file App\HttpController\Router.php:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/8/15
  6. * Time: 上午10:39
  7. */
  8. namespace App\HttpController;
  9. use EasySwoole\Http\AbstractInterface\AbstractRouter;
  10. use FastRoute\RouteCollector;
  11. use EasySwoole\Http\Request;
  12. use EasySwoole\Http\Response;
  13. class Router extends AbstractRouter
  14. {
  15. function initialize(RouteCollector $routeCollector)
  16. {
  17. $routeCollector->get('/user', '/index.html');
  18. $routeCollector->get('/rpc', '/Rpc/index');
  19. $routeCollector->get('/', function (Request $request, Response $response) {
  20. $response->write('this router index');
  21. });
  22. $routeCollector->get('/test', function (Request $request, Response $response) {
  23. $response->write('this router test');
  24. return '/a';//Relocate to the /a method
  25. });
  26. $routeCollector->get('/user/{id:\d+}', function (Request $request, Response $response) {
  27. $response->write("this is router user ,your id is {$request->getQueryParam('id')}");//Get the id of the route match
  28. return false;//No longer request, end this response
  29. });
  30. }
  31. }

Visit 127.0.0.1:9501/rpc, corresponding to App\HttpController\Rpc.php->index()

::: warning If the callback function is used to process the route, return false means that the request is not continued, and the method afterAction, gc cannot be triggered. :::

Implementation principle can be viewed in the source code

Routing Group

  1. class Router extends AbstractRouter
  2. {
  3. function initialize(RouteCollector $routeCollector)
  4. {
  5. $routeCollector->addGroup('/admin',function (RouteCollector $collector){
  6. $collector->addRoute('GET','/index.html',function (Request $request,Response $response){
  7. $version = $request->getQueryParam('version');
  8. // Here you can return the path according to the version parameter
  9. if($version == 1){
  10. $path = '/V1'.$request->getUri()->getPath();
  11. }else{
  12. $path = '/V2'.$request->getUri()->getPath();
  13. }
  14. //New path
  15. return $path;
  16. });
  17. });
  18. }
  19. }

Global Mode Intercept

Add the following code in Router.php to enable global mode interception

  1. $this->setGlobalMode(true);

Under global mode interception, the route will only match the controller method response in Router.php, and the default parsing of the framework will not be performed.

Exception error handling

The following two methods can be used to set the route matching error and the callback of the method not found:

  1. <?php
  2. $this->setMethodNotAllowCallBack(function (Request $request,Response $response){
  3. $response->write('No processing method found');
  4. return false;//End this response
  5. });
  6. $this->setRouterNotFoundCallBack(function (Request $request,Response $response){
  7. $response->write('Route matching not found');
  8. return 'index';//Redirect to index route
  9. });

::: warning The callback function is only for the fastRoute unmatched condition. If the callback does not end the request response, the request will continue to Dispatch and try to find the corresponding controller for response processing. :::

fastRoute use

addRoute method

The prototype of the addRoute method that defines the route is as follows. This method requires three parameters. Below we have a deeper understanding of the routing components.

  1. $routeCollector->addRoute($httpMethod, $routePattern, $handler)

httpMethod


This parameter needs to pass in an uppercase HTTP method string, specifying the method that the route can intercept. A single method directly passes the string. You need to intercept multiple methods to pass in a one-dimensional array, as in the following example:

  1. // Intercept GET method
  2. $routeCollector->addRoute('GET', '/router', '/Index');
  3. // Intercept POST method
  4. $routeCollector->addRoute('POST', '/router', '/Index');
  5. // Intercept multiple methods
  6. $routeCollector->addRoute(['GET', 'POST'], '/router', '/Index');

routePattern


Passing a route matching expression, the route that meets the expression requirements will be intercepted and processed. The expression supports placeholder matching such as {parameter name: matching rule}, which is used to qualify routing parameters.

Basic match

The following definition will match http://localhost:9501/users/info

  1. $routeCollector->addRoute('GET', '/users/info', 'handler');

Binding parameters

The following definition takes the part after /users/ as a parameter, and the qualified parameter can only be the number [0-9]

  1. // can match: http://localhost:9501/users/12667
  2. // Can't match: http://localhost:9501/users/abcde
  3. $routeCollector->addRoute('GET', '/users/{id:\d+}', 'handler');

The following definitions are not restricted, only the matching URL part is taken as a parameter.

  1. // can match: http://localhost:9501/users/12667
  2. // can match: http://localhost:9501/users/abcde
  3. $routeCollector->addRoute('GET', '/users/{name}', 'handler');

Sometimes the partial location of the route is optional and can be defined as follows

  1. // can match: http://localhost:9501/users/to
  2. // can match: http://localhost:9501/users/to/username
  3. $routeCollector->addRoute('GET', '/users/to[/{name}]', 'handler');

::: warning The bound parameters will be assembled into the get data by the inside of the framework. :::

  1. <?php
  2. $routeCollector->get('/user/{id:\d+}', function (Request $request, Response $response) {
  3. $response->write("this is router user ,your id is {$request->getQueryParam('id')}");
  4. return false;
  5. });

handler


Specify the method that needs to be processed after the route is successfully matched. You can pass in a closure. When passing in the closure, you must pay attention to the end of the response after processing. Otherwise, the request will continue to Dispatch to find the corresponding controller to handle. Of course, if you take advantage of this, you can also process some requests and then pass them to the controller execution logic.

  1. // Incoming closures
  2. $routeCollector->addRoute('GET', '/router/{id:\d+}', function (Request $request, Response $response) {
  3. $id = $request->getQueryParam('id');
  4. $response->write('Userid : ' . $id);
  5. Return false;
  6. });

Can also be directly passed to the controller path

  1. $routeCollector->addRoute('GET', '/router2/{id:\d+}', '/Index');

::: warning For more details on usage, please check the FastRouter directly. :::