Laravel中正确地返回HTTP状态码方法示例

yipeiwu_com6年前PHP代码库

在 API 中返回状态码是很重要的,因为响应处理程序是工作在 API 的响应状态码之上的。

写 API 时其中有一个重要的地方是更好的处理响应状态码。以前,我一般会使用不常用的 Integer 类型数字作为 HTTP 状态码 。看下面的这个例子:

<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Post;
Class PostsController extends Controller{
 public function store(){
 $post = new Post(request()->only('title', 'description'));
 request()->user()->posts()->save($post);
 return response()->json(['post' => $post], 201);
 }
}

在 API 的调用期间 ,如果数据已被创建,那么将会响应 HTTP 201 状态码,但是很多的开发者并不知道 201 状态码,他们更熟悉 200 成功状态码 。使用 Symfony Response 类可以解决这个问题 。它包含了所有的 HTTP 状态码,并且使用更简单易懂的命名 。以上的代码可以修改为如下代码:

<?php 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Post;
use Symfony\Component\HttpFoundation\Response;
Class PostsController extends Controller{
 public function store(){
 $post = new Post(request()->only('title', 'description'));
 request()->user()->posts()->save($post);
 return response()->json(['post' => $post], Response::HTTP_CREATED);
 }
}

这个类包含了所有定义的 HTTP 状态码,先来看看其中的一些状态码:

虽然我不觉得直接写数值的 HTTP 状态码是一个坏习惯,但是使用

HTTP 状态码时用一些不解自明的命名会更好。大家编码快乐!

原文地址:https://medium.com/@naumancs/how-to-use-...

译文地址:https://learnku.com/laravel/t/9684/how-t...

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【宜配屋www.yipeiwu.com】的支持。

相关文章

php使用ftp远程上传文件类(完美解决主从文件同步问题的方法)

php使用ftp实现文件上传代码片段: <?php /** * ftp上传文件类 */ class Ftp { /** *...

PHP下利用shell后台运行PHP脚本,并获取该脚本的Process ID的代码

复制代码 代码如下:$command = '/usr/bin/php /pub/www/u111/job/Crondo/auto_collector.php &'; $process =...

PHP警告Cannot use a scalar value as an array的解决方法

看到php的错误日志里有些这样的提示: [27-Aug-2011 22:26:12] PHP Warning: Cannot use a scalar value as an array...

thinkphp的CURD和查询方式介绍

对数据的读取 Read复制代码 代码如下:$m=new Model('User'); $m=M('User'); select $m->select();//获取所有数据,以数组形...

PHP统一页面编码避免乱码问题

页面编码统一 MySQL数据库编码、html页面编码、PHP或html文件本身编码要全部一致。 1、MySQL数据库编码: 建立数据库时指定编码(如gbk_chinese_ci),建立...