以下是一个使用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的文章