路由配置文件 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"}