Home > front end >  How can I block my code without using die statements?
How can I block my code without using die statements?

Time:01-13

Hi guys I am making a simple PHP API using McCock architecture-like structures, in my products controller I have a function to create a new product like this

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

The problem is: If I only use echo to display messages at the end of a condition it does not stop the code from running like a return statement, but If I use return instead of echo, the code will display no messages

How can I solve this without using die() statements?

Thanks for helping out

CodePudding user response:

You can simply return after the echo:

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

Basically if create returns a falsy value, then it failed, otherwise it succeeded. You could also decide to throw an Exception instead, like:

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;
}
  •  Tags:  
  • php
  • Related