A functioning API is built upon receiving requests and returning a consumable response to the client. An API will generally return responses in an easy to consume format such as JSON. There's a number of different ways to return responses and it will largely depend on how complex your API is or will become.
一个运行的 API 主要是获取请求并返回给客户端响应信息。一个 API 通常会以一种易于使用的格式返回响应,例如 JSON。这是一个不同的方法去返回请求。这里有许多不同的方法可以返回响应,很大程度上取决于您的 API 的复杂程度或者 API 未来的方向。
The easiest way to return a consumable response is to simply return an array or object directly from your controller. Not every object can be correctly formatted though so you should ensure that it implements either the ArrayObject or the
interface.
- Illuminate\Support\Contracts\ArrayableInterface
返回一个可使用的响应最简单的方式是直接从控制器返回数组或对象。不是每个对象都能够被返回正确的格式,但因此,你应该确定它继承了 ArrayObject 或者 Illuminate\Support\Contracts\ArrayableInterface 接口。
- class UserController
- {
- public function index()
- {
- return User::all();
- }
- }
在这个实例中,我们的 User 类继承了 Illuminate\Database\Eloquent\Model,意味着它能作为一个格式化的数组返回,所以我们能通过调用 User::all(), 简单的返回一个 users 集合。
同样的,你也能使用它返回一个单一的 user。例:如下
- class UserController
- {
- public function show($id)
- {
- return User::findOrFail($id);
- }
- }
这个包,将自动格式化响应信息之后作为 JSON 格式返回,并且为 Content-Type 头设置为 application/json。
这个响应构建器,提供一个流畅的接口去简单的生成一个定制的响应信息。这个响应构建器通常与 transformers 结合使用。
要想在你的控制器,使用这个响应返回。你应该引入(使用) Dingo\Api\Routing\Helpers。为了让你的全部控制器都可以用使用这个特性,你应该创建一个基类控制器,让你所有的控制器都去继承(extends)它。
- use Dingo\Api\Routing\Helpers;
- use Illuminate\Routing\Controller;
- class BaseController extends Controller
- {
- use Helpers;
- }
现在,你的控制器能简单的继承基本控制器。在你的控制器中可以经由 $response 属性来访问响应构建器。
关于这,更详细的文档,你应该看 Transformers 那节。(接下来,我会慢慢翻译的,等。。)
Responding With A Single Item 作为一个 item 返回
- class UserController extends BaseController
- {
- public function show($id)
- {
- $user = User::findOrFail($id);
- return $this->response->array($user->toArray());
- }
- }
- class UserController extends BaseController
- {
- public function show($id)
- {
- $user = User::findOrFail($id);
- return $this->response->item($user, new UserTransformer);
- }
- }
- class UserController extends BaseController
- {
- public function index()
- {
- $users = User::all();
- return $this->response->collection($users, new UserTransformer);
- }
- }
- class UserController extends BaseController
- {
- public function index()
- {
- $users = User::paginate(25);
- return $this->response->paginator($users, new UserTransformer);
- }
- }
- return $this - >response - >noContent();
- return $this - >response - >created();
你也可以,为这个 created 随意的提供一个值,作为第一个参数。
- return $this - >response - >created($location);
这个包内有很多不同的响应错误的提示,你可以快速的形成一个错误提示。(这块文字理解,我感觉不太好,就把真实的返回值写出来了)
- return $this - >response - >error('This is an error.', 404);
- 返回信息:{"message":"This is an error.","status_code":404}
- return $this - >response - >errorNotFound();
- 返回信息:{"message":"Not Found","status_code":404}
- return $this - >response - >errorBadRequest();
- 返回信息:{"message":"Bad Request","status_code":400}
- return $this - >response - >errorForbidden();
返回信息:{"message":"Forbidden","status_code":403}
- return $this - >response - >errorInternal();
返回信息:{"message":"Internal Error","status_code":500}
- return $this - >response - >errorUnauthorized();
返回信息:{"message":"Unauthorized","status_code":401}
一旦您使用了上述方法中的一个,您就可以通过添加附加的表头来进一步定制响应。
- return $this - >response - >item($user, new UserTransformer) - >withHeader('X-Foo', 'Bar');
某些转化层可能会使用元数据(meta data)。当你需要提供与资源相关的额外数据时,这很有用。
- return $this - >response - >item($user, new UserTransformer) - >addMeta('foo', 'bar');
你也可以设置一个 meta 数据的数组,省得多次调用 addMeta 方法。
- return $this - >response - >item($user, new UserTransformer) - >setMeta($meta);
- return $this - >response - >item($user, new UserTransformer) - >setStatusCode(200);
在这个配置章节,我们简单的讲解了返回信息格式。通过这个 dingo 包,我们将自动的使用 json 格式,并设置一个恰当的 Content-Type 头。除了 JSON 格式化,还有一个 JSONP 格式化。这个 formatter 将会用一个回调包裹响应。更改格式只需要简单将配置文件(Laravel)或启动文件(Lumen)中的默认 JSON 格式替换成 JSONP 即可:
- 'formats' => [
- 'json' => 'Dingo\Api\Http\Response\Format\Jsonp'
- ]
或
- Dingo\Api\Http\Response: :addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp);
你可以注册之后使用你自己需要的格式。你的格式应该继承 Dingo\Api\Http\Response\Format\Format。这有很多请求应该被定义:formatEloquentModel,formatEloquentCollection,formatArray 和 getContentType。
在发送一个响应之前,它会改变它,在发送。这个过程包括运行所有转换器(Transformer)以及通过配置的响应格式发送响应。如果你需要对响应的变化有更多的控制,你可以使用 ResponseWasMorphed 和 ResponseIsMorphing 这两个事件.
在你的 app/Listeners 文件夹,创建一个监听器。
- use Dingo\Api\Event\ResponseWasMorphed;
- class AddPaginationLinksToResponse
- {
- public function handle(ResponseWasMorphed $event)
- {
- if (isset($event->content['meta']['pagination'])) {
- $links = $event->content['meta']['pagination']['links'];
- $event->response->headers->set(
- 'link',
- sprintf('<%s>; rel="next", <%s>; rel="prev"', $links['links']['next'], $links['links']['previous'])
- );
- }
- }
- }
然后通过在
中注册事件及其对应监听器来监听该事件:
- EventServiceProvider
- protected $listen = [
- 'Dingo\Api\Event\ResponseWasMorphed' => [
- 'App\Listeners\AddPaginationLinksToResponse'
- ]
- ];
Now all responses that contain pagination links will also add these links to the Link header.(这句话,留给你们翻译)
这章结束了,马上要 2018 年了。新的一年,go go go !!!
来源: https://www.cnblogs.com/jingying/p/8041790.html