search
HomeBackend DevelopmentPHP TutorialLaravel & Lumen RESTFul API 扩展包:Dingo API(三) -- Response(响应)

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

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

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

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

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

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;}

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

数组响应

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

单个Item响应

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();

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

return $this->response->created($location);

错误响应

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

// 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();

添加额外的响应头

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

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

添加元数据

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

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

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

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

设置响应状态码

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

2、自定义响应格式

在安装配置中我们已经简单接触过响应格式,默认情况下Dingo API会自动使用JSON格式并设置相应的 Content-Type头。除了JSON之外还有一个JSONP格式,改格式会将响应封装到一个回调中。要注册改格式只需要简单将配置文件(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);

默认情况下回调参数默认查询字符串是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'])            );        }    }}

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

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

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

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

Statement
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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment