hyperf搭建http服务结合模型实现文章管理接口代码示例

以下是一个使用Hyperf搭建HTTP服务结合模型实现文章管理接口的代码示例:

1. 首先,创建一个Article模型类,用于定义文章的属性和方法:

<?php

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

class  Article  extends  Model {

protected $table = 'articles';

protected $fillable = ['title', 'content'];

// 定义关联关系等其他方法...

}

2. 然后,创建一个ArticlesController控制器类,用于处理文章相关的HTTP请求:

<?php

namespace App\Controller;

use App\Model\Article;

use Hyperf\HttpServer\Annotation\Controller;

use Hyperf\HttpServer\Annotation\GetMapping;

use Hyperf\HttpServer\Annotation\PostMapping;

use Hyperf\HttpServer\Annotation\PutMapping;

use Hyperf\HttpServer\Annotation\DeleteMapping;

use Hyperf\HttpServer\Contract\RequestInterface;

/** * @Controller(prefix="/articles") */

class ArticlesController {

/** * @GetMapping("/") */

public function index() {

// 获取所有文章列表

$articles = Article::query()->get();

return $articles;

}

/** * @PostMapping("/") */

public function store(RequestInterface $request) {

// 创建一篇新文章

$article = Article::create($request->all());

return $article;

}

/** * @PutMapping("/{id}") */

public function update(RequestInterface $request, $id) {

// 更新指定id的文章

$article = Article::findOrFail($id);

$article->update($request->all());

return $article;

}

/** * @DeleteMapping("/{id}") */

public function destroy($id) {

// 删除指定id的文章

$article = Article::findOrFail($id);

$article->delete();

return ['message' => '删除成功'];

}

}

 最后,将ArticlesController添加到路由配置文件routes.php中:

use App\Controller\ArticlesController; use Hyperf\HttpServer\Router\Router; Router::addRoute(['GET', 'POST', 'PUT', 'DELETE'], '/articles', [ArticlesController::class, 'index']); Router::addRoute(['POST'], '/articles', [ArticlesController::class, 'store']); Router::addRoute(['PUT'], '/articles/{id}', [ArticlesController::class, 'update']); Router::addRoute(['DELETE'], '/articles/{id}', [ArticlesController::class, 'destroy']);

现在,你可以使用Hyperf的HTTP服务来访问并测试文章管理接口了。例如:

  • GET /articles 获取所有文章列表
  • POST /articles 创建一篇新文章
  • PUT /articles/{id} 更新指定id的文章
  • DELETE /articles/{id} 删除指定id的文章

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值