zlob / php-json-server
简单的REST API json服务器
1.1.0
2015-08-13 16:56 UTC
Requires
- php: >=5.5.9
- doctrine/inflector: ^1.0
- fzaninotto/faker: 1.5.*
- nikic/php-parser: ~1.0
- symfony/console: 2.7.*
- symfony/http-foundation: 2.7.*
Requires (Dev)
- codeclimate/php-test-reporter: ~0.1.2
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-09-10 15:25:28 UTC
README
易于使用的库,只需几分钟即可提供REST API服务器。为需要快速后端进行原型设计的 frontend 开发者而创建。可以与您喜欢的php web框架一起使用。
灵感来源于JSON Server
不适用于生产
安装
通过composer: composer require zlob/php-json-server
##示例
您可以使用此库与任何php web框架。以下是如何将其与Laravel 5.1集成的示例
- 首先,您需要创建一个控制器,我们将在此控制器中使用php-json-server
<?php namespace App\Http\Controllers; use Request; use Response; use Config; use JsonServer\JsonServer; class JsonServerController extends Controller { public function handleRequest($uri) { $data = Request::all(); //request data $method = Request::method(); //request method $jsonServer = new JsonServer(); //create new JsonServer instance $response = $jsonServer->handleRequest($method, $uri, $data); //handle request //return Symfony\Component\HttpFoundation\Response //object with content, status and headers $response->send(); //send response } }
- 然后,向routes.php文件添加新的路由,将'/api/*'路由与我们的控制器方法handleRequest链接
Route::any('api/{all}', "JsonServerController@handleRequest")->where('all', '.*');
- 最后,我们可以选择性地用一些数据填充我们的数据库。为此,打开php-json-server/db/db.json文件并添加一些数据
{ "posts": [ { "id": 1, "title": "json-server", "author": "zlob" }, { "id": 2, "title": "json-server", "author": "zlob" } ], "comments": [ { "id": 1, "body": "some comment", "post_id": 1 } ] }
- 就这样!现在,如果您访问"/api/posts",您将得到{ "id": 1, "title": "json-server", "author": "zlob" }
基于之前的db.json文件,以下是所有路由
GET /posts
GET /posts/1
GET /posts/1/comments
POST /posts
PUT /posts/1
PATCH /posts/1
DELETE /posts/1
过滤资源
GET /posts?title=json-server&author=zlob
截取资源,添加_start
和_end
或_limit
(响应中包含X-Total-Count头)。
GET /posts?_start=20&_end=30
GET /posts/1/comments?_start=0&_end=30
排序资源,添加_sort
和_order
(默认为升序)。
GET /posts?_sort=views&_order=desc
GET /posts/1/comments?_sort=votes&_order=asc
对资源进行全文搜索,添加_query
。
GET /posts?_query=internet
嵌入其他资源,添加_embed
(多个资源用逗号分隔)。
GET /posts/1?_embed=comments
GET /posts/1?_embed=comments,tags
CLI: 生成随机数据
您可以使用一个命令填充数据库中的假数据。例如,要在jsonServer目录中创建包含标题、日期、作者和内容的50个资源的posts表,使用以下命令
php-json-server faker posts 'title.text date.date author.name content.text.10' --num=50
其中字段由空格分隔,字段名、字段类型和附加参数由点分隔。字段类型和参数描述在faker中,它被内部使用。
许可协议
MIT - Zlob