Php 正在设置HTTP请求的状态

Php 正在设置HTTP请求的状态,php,laravel,Php,Laravel,当发出请求时,我尝试在自定义API中设置http状态 protected $statusCode = 200; public function setStatusCode($statusCode) { $this->statusCode = $statusCode; return $this; } public function respond($data, $headers = []) { return response()-&

当发出请求时,我尝试在自定义API中设置http状态

protected $statusCode = 200;

public function setStatusCode($statusCode) {
        $this->statusCode = $statusCode;
        return $this;
    }

public function respond($data, $headers = []) {
        return response()->json($data, $this->getStatusCode(), $headers);
    }

public function respondCreated($message) {
    return $this->setStatusCode(201)->respond([
        'message' => $message
    ]);
}

$this->respondCreated("Incident was created");
但是,当我在POSTMAN中发出服务器请求时,我看到的是上面代码中设置的状态200而不是201,消息根本没有出现。我需要用不同的方式吗

我使用的是Laravel框架,并通过《构建你不会讨厌的API》一书实现了这些功能

我按照建议使用了
http\u response\u code()
方法,并将代码设置如下:

public function respondCreated($message) {
    $this->setStatusCode(201)->respond([
        'message' => $message
    ]);
    http_response_code(201);
    return $this;
}
当我返回正确显示的响应代码时,邮递员状态仍然是200

laravel的助手方法是
response()
,描述如下:

Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, providing a variety of methods for building HTTP responses:

use Illuminate\Http\Response;

Route::get('home', function () {
    return (new Response($content, $status))
                  ->header('Content-Type', $value);
});
For convenience, you may also use the response helper:

Route::get('home', function () {
    return response($content, $status)
                  ->header('Content-Type', $value);
});


您可以按照中的说明设置HTTP响应代码



设置实际HTTP状态代码头的代码在哪里?嗯。。。好。。。我需要怎么设置这个?我不知道。什么是
response()
->json()
以及其他什么呢。。。!?我在理解“respondCreated”方法如何将其返回值正确地传递给客户机时遇到了一些问题。我使用respond方法,但我想我遗漏了一些东西。我看你使用的是一个框架,你不知道它的内部结构。你能至少编辑一下这个问题并说出它是什么样的框架吗?发布一个他如何做到这一点的例子,而不是仅仅发布一个链接。这个方法很容易使用,没有重载,而且我没有询问者的完整类来提供完整的例子。我不认为在这里为一个方法提供罗马人有任何意义。如果PHP改变了它的文档站点,你的答案将不再有用。OP努力添加了他们的代码片段,让我们为他们和未来的读者添加一些见解。另外,正如在OP代码中看到的,他实际上在他们的代码中使用了这个方法。
<?php

// Get the current default response code
var_dump(http_response_code()); // int(200)

// Set our response code
http_response_code(404);

// Get our new response code
var_dump(http_response_code()); // int(404)
?>