其他分享
首页 > 其他分享> > hyperf 路由

hyperf 路由

作者:互联网

路由配置文件 config/routes.php

<?php
use Hyperf\HttpServer\Router\Router;

// 下面三种方式的任意一种都可以达到同样的效果
Router::get('/hello-hyperf', 'App\Controller\IndexController::hello');
Router::get('/hello-hyperf', 'App\Controller\IndexController@hello');
Router::get('/hello-hyperf', [App\Controller\IndexController::class, 'hello']);

路由方法

use Hyperf\HttpServer\Router\Router;

// 注册与方法名一致的 HTTP METHOD 的路由
Router::get($uri, $callback);
Router::post($uri, $callback);
Router::put($uri, $callback);
Router::patch($uri, $callback);
Router::delete($uri, $callback);
Router::head($uri, $callback);

// 注册任意 HTTP METHOD 的路由
Router::addRoute($httpMethod, $uri, $callback);

路由组

Router::addGroup('/user/',function (){
    Router::get('index','App\Controller\UserController@index');
    Router::post('store','App\Controller\UserController@store');
    Router::get('update','App\Controller\UserController@update');
    Router::post('delete','App\Controller\UserController@delete');
});

实例

控制器 app/Controller/UserController.php

<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;

class UserController
{
        public function index(RequestInterface $request)
        {
                $id = $request->input('id',1);
                return ['msg'=>'route test','id'=>$id];
        }
}

路由配置文件 config/routes.php

<?php

declare(strict_types=1);

use Hyperf\HttpServer\Router\Router;
Router::get('/user', 'App\Controller\UserController::index');

测试

curl 118.195.173.53:9501/user?id=2

结果显示

{"msg":"route test","id":"2"}

案例2 注解方式

<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;

/**
 * @AutoController()
 */
class UserController
{
        public function index(RequestInterface $request)
        {
                $id = $request->input('id',1);
                return ['msg'=>'route test','id'=>$id];
        }
}
curl 118.195.173.53:9501/user/index?id=3

结果显示

{"msg":"route test","id":"3"}

标签:Controller,uri,callback,hyperf,Router,id,路由
来源: https://www.cnblogs.com/hu308830232/p/15277149.html