Hyperf 注解及路由

本文介绍了Hyperf框架中的路由定义,包括传统方式和通过注解的方式。重点讲解了如何使用注解如@Controller和@RequestMapping等来设定路由,并提到了PHPStorm的IDE注解插件PHP Annotations的安装和使用,以及在不同情况下URL的构建规则。

由于Hyperf只能运行在Linux和Mac上  所以要用到PHPstrom的ftp上传及下载

1.Hyperf的传统路由定义在app\config\routes.php下的,配置方式和laravel是一样的,这个就不过多的讲解了

2.Hyperf通过注解的方式定义路由(首先我们需要下载phpstrom的IDE注解插件PHP Annotations),在PHPstrom设置的Plugins 中搜索 PHP Annotations,下载重启PHPstrom

@AutoController()  注解会自动根据类名及方法名创建对应的URL 

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;

/**
 * @AutoController(prefix="user")
 *  prefix参数会重定义类名  使Url自定义
 */
class IndexController extends AbstractController
{
    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }
}

如果没有加prefix参数的话 url是http://localhost:9501/index/index

如果定义了prefix参数  url就是 http://localhost:9501/user/index

如果类名是IndexDiController这样驼峰式并且没有配prefix参数的话   url是http://localhost:9501/index_di/index

@Controller()  注解

@Controller()注解需要搭配 @RequestMapping()   @GetMapping()  @PutMapping() @PostMapping()等注解来一起使用

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * @Controller(prefix="index")
 */
class IndexController extends AbstractController
{
    /**
     * @RequestMapping(path="index", methods={"get","post"})
     * #path规定了路由里对应该方法的名称,methods则规定了访问的方式
     * 注意参数要带引号而且必须是双引号
     */
    public function index()
    {
        $user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值