Laravel & 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头。
注意:目前该功能还在开发阶段,不建议用于生产环境。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The arrow function was introduced in PHP7.4 and is a simplified form of short closures. 1) They are defined using the => operator, omitting function and use keywords. 2) The arrow function automatically captures the current scope variable without the use keyword. 3) They are often used in callback functions and short calculations to improve code simplicity and readability.
