嗨,伙计们,我正在制作一个简单的PHP API,使用McCock架构式结构,在我的产品控制器中,我有一个创建新产品的函数,像这样
public function create()
{
$data = json_decode(file_get_contents("php://input"));
$product = $this->model('Product');
if (empty($data->name) || empty($data->co2_value)) {
http_response_code(400);
echo json_encode(
array("message" => "Bad Request")
);
die();
}
//...
}
问题是:如果我只使用echo
在条件的末尾显示消息,它不会阻止代码像return
语句一样运行,但是如果我使用return而不是echo,代码将不显示消息
不使用die()
语句如何解决这个问题?
谢谢你的帮助
您可以简单地在echo
之后添加return
:
public function create()
{
$data = json_decode(file_get_contents("php://input"));
$product = $this->model('Product');
if (empty($data->name) || empty($data->co2_value)) {
http_response_code(400);
echo json_encode(
array("message" => "Bad Request")
);
return null;
}
//...
return $product;
}
基本上,如果create
返回假值,则失败,否则成功。您还可以决定改为throw
和Exception
,如:
public function create()
{
$data = json_decode(file_get_contents("php://input"));
$product = $this->model('Product');
if (empty($data->name) || empty($data->co2_value)) {
http_response_code(400);
throw new Exception(json_encode(
array("message" => "Bad Request")
));
}
//...
return $product;
}