Swoole框架Hyperf(三) - 控制器与路由

当我们通过ip+端口用浏览器访问时候,是访问了控制器app/Controller/IndexController.php/index

它是由config/routes.php配置的
在这里插入图片描述
现在,我们新建一个控制器访问试试吧!
但是,传统路由配置就不用讲了吧,一看就懂。
所以,我们用注解来配置路由。
注解是什么?
你就理解为是在控制器里面配置路由的一种方法。

@AutoController 注解,自动生成路由
app/Controller/新建一个UserController.php

<?php
declare(strict_types=1); // php严格模式

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface; // 接收请求
use Hyperf\HttpServer\Annotation\AutoController; // 自动路由

/**
 * 下面的注释不能去掉,它是有作用的,也就是注解
 * @AutoController()
 */
class UserController
{
    // Hyperf 会自动为此方法生成一个 /user/index 的路由,允许通过 GET 或 POST 方式请求
    public function index(RequestInterface $request)
    {
        // 从请求中获得 id 参数
        $id = $request->input('id', 1);
        return (string)$id;
    }
}

重启hyperf服务
在这里插入图片描述
在这里插入图片描述
@Controller 注解,配置路由
还是在UserController.php里,覆盖代码

<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * @Controller()
 */
class UserController
{
    // Hyperf 会自动为此方法生成一个 /user/index 的路由,允许通过 GET 或 POST 方式请求
    /**
     * @RequestMapping(path="index", methods="get,post")
     */
    public function index(RequestInterface $request)
    {
        // 从请求中获得 id 参数
        $id = $request->input('id', 1);
        return (string)$id;
    }
}

记得修改了代码后要重启服务哦!
在这里插入图片描述
必须的

/**
 * @Controller()
 */
/**
  * @RequestMapping(path="index", methods="get,post")
  */

@Controller()表明这是控制器
@RequestMapping是配置项,我们可以修改path,把index改成index2,再进行访问
重启服务
你会发现,index访问不了了,而index2可以访问。
甚至你还可以这样改

/**
  * @RequestMapping(path="/abc/index2", methods="get,post")
  */

重启服务
在这里插入图片描述
path/ 开头时,表示从根目录开始,你想配置成什么就什么。

methods是允许的请求类型。

Hyperf框架系列列表

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值