Table of Contents
1、响应构建器
数组响应
单个Item响应
集合响应
分页响应
无内容响应
创建响应
错误响应
添加额外的响应头
添加元数据
设置响应状态码
2、自定义响应格式
3、Morphing 和 Morphed事件
Home Backend Development PHP Tutorial Laravel & Lumen RESTFul API 扩展包:Dingo API(三) -- Response(响应)

Laravel & Lumen RESTFul API 扩展包:Dingo API(三) -- Response(响应)

Jun 20, 2016 pm 12:32 PM

一个API的功能主要是获取请求并返回响应给客户端,响应的格式是多样的,比如JSON,返回响应的方式也是多样的,这取决于当前构建的API的复杂度以及对未来的考量。

返回响应最简单的方式是直接从控制器返回数组或对象,但不是每个响应对象都能保证格式正确,所以你要确保它们实现了 ArrayObject或者 Illuminate\Support\Contracts\ArrayableInterface接口:

class UserController{    public function index()    {        return User::all();    }}
Copy after login

在本例中, User类继承自 Illuminate\Database\Eloquent\Model,这意味着返回的是可以被格式化为数组的数据,当然也可以返回单个用户:

class UserController{    public function show($id)    {        return User::findOrFail($id);    }}
Copy after login

Dingo API会自动将响应格式化为JSON格式并设置 Content-Type头为 application/json。

1、响应构建器

响应构建器提供了平滑的接口以便我们轻松构建更多自定义的响应。响应构建器通常与转换器(Transformer)一起使用。

要使用响应构建器控制器需要使用 Dingo\Api\Routing\Helperstrait,为了让每个控制器都可以使用这个trait,我们将其放置在API基类控制器 Controller中:

use Dingo\Api\Routing\Helpers;use Illuminate\Routing\Controller;class BaseController extends Controller{    use Helpers;}
Copy after login

现在可以定义一个继承自该控制器的控制器,在这些控制器中可以通过 $response属性来访问响应构建器。

数组响应

class UserController extends BaseController{    public function show($id)    {        $user = User::findOrFail($id);        return $this->response->array($user->toArray());    }}
Copy after login

单个Item响应

class UserController extends BaseController{    public function show($id)    {        $user = User::findOrFail($id);        return $this->response->item($user, new UserTransformer);    }}
Copy after login

集合响应

class UserController extends BaseController{    public function index()    {        $users = User::all();        return $this->response->collection($users, new UserTransformer);    }}
Copy after login

分页响应

class UserController extends BaseController{    public function index()    {        $users = User::paginate(25);        return $this->response->paginator($users, new UserTransformer);    }}
Copy after login

无内容响应

return $this->response->noContent();
Copy after login

创建响应

return $this->response->created();
Copy after login

还可以将位置信息作为创建资源的第一个参数:

return $this->response->created($location);
Copy after login

错误响应

你可以使用多种内置错误生成错误响应:

// A generic error with custom message and status code.return $this->response->error('This is an error.', 404);// A not found error with an optional message as the first parameter.return $this->response->errorNotFound();// A bad request error with an optional message as the first parameter.return $this->response->errorBadRequest();// A forbidden error with an optional message as the first parameter.return $this->response->errorForbidden();// An internal error with an optional message as the first parameter.return $this->response->errorInternal();// An unauthorized error with an optional message as the first parameter.return $this->response->errorUnauthorized();
Copy after login

添加额外的响应头

使用了上述方法之后还可以通过添加响应头来自定义响应:

return $this->response->item($user, new UserTransformer)->withHeader('X-Foo', 'Bar');
Copy after login

添加元数据

某些转化层可能会使用元数据(meta data),这在你需要提供额外与资源关联的数据时很有用:

return $this->response->item($user, new UserTransformer)->addMeta('foo', 'bar');
Copy after login

还可以设置元数据数组替代多个方法链的调用:

return $this->response->item($user, new UserTransformer)->setMeta($meta);
Copy after login

设置响应状态码

return $this->response->item($user, new UserTransformer)->setStatusCode(200);
Copy after login

2、自定义响应格式

在安装配置中我们已经简单接触过响应格式,默认情况下Dingo API会自动使用JSON格式并设置相应的 Content-Type头。除了JSON之外还有一个JSONP格式,改格式会将响应封装到一个回调中。要注册改格式只需要简单将配置文件(Laravel)或启动文件(Lumen)中的默认JSON格式替换成JSONP即可:

'formats' => [    'json' => 'Dingo\Api\Http\Response\Format\Jsonp']
Copy after login

或者:

Dingo\Api\Http\Response::addFormatter('json', new Dingo\Api\Http\Response\Format\Jsonp);
Copy after login

默认情况下回调参数默认查询字符串是callback,这可以通过修改构造函数的第一个参数来设置。如果查询字符串不包含任何参数将会返回JSON响应。

你还可以注册并使用自己需要的响应格式,自定义的格式对象需要继承自 Dingo\Api\Http\Response\Format\Format类,同时还要实现如下这些方法: formatEloquentModel, formatEloquentCollection, formatArray以及 getContentType。

3、Morphing 和 Morphed事件

在Dingo API发送响应之前会先对该响应进行转化(morph),这个过程包括运行所有转换器(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'])            );        }    }}
Copy after login

然后通过在 EventServiceProvider中注册事件及其对应监听器来监听该事件:

protected $listen = [    'Dingo\Api\Event\ResponseWasMorphed' => [        'App\Listeners\AddPaginationLinksToResponse'    ]];
Copy after login

现在所有包含分页链接的响应也会将这些链接添加到 Link头。

注意:目前该功能还在开发阶段,不建议用于生产环境。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles