I am using FuelPHP's rest controller.

I am trying to break the flow and display my response after encountering an error.

Here is my basic flow needed:

  1. When any of the methods are called I run a "validate" function, which validates parameters and other business logic.
  2. If the "validate" function determines something is off, I want to stop the entire script and display the errors I have complied so far.

I have tried the following in my "validate" function but it simply exits the validate function... then continues to the initial method being requested. How do I stop the script immediately and display the contents of this response?

return $this->response( array(
        'error_count' => 2,
        'error' => $this->data['errors'] //an array of error messages/codes
    ) );
有帮助吗?

解决方案

That is very bad practice. If you exit you not only abort the current controller, but also the rest of the framework flow.

Just validate in the action:

// do your validation, set a response and return if it failed
if ( ! $valid)
{
    $this->response( array(
        'error_count' => 2,
        'error' => $this->data['errors'] //an array of error messages/codes
    ), 400); //400 is an HTTP status code
    return;
}

Or if you want to do central validation (as opposed to in the controller action), use the router() method:

public function router($resource, $arguments)
{
    if ($this->valid_request($resource))
    {
        return parent::router($resource, $arguments);
    }
}

protected function valid_request($resource)
{
    // do your validation here, $resource tells you what was called
    // set $this->response like above if validation failed, and return false
    // if valid, return true
}

其他提示

I am new to FuelPHP so if this method is bad practice, let me know.

If you want your REST controller to break the flow at some other point than when the requested method returns something, use this code. You can change the $this->response array to return whatever you want. The main part of the script is the $this->response->send() method and exit method.

    $this->response( array(
        'error_count' => 2,
        'error' => $this->data['errors'] //an array of error messages/codes
    ), 400); //400 is an HTTP status code

    //The send method sends the response body to the output buffer (i.e. it is echo'd out).
    //pass it TRUE to send any defined HTTP headers before sending the response body.

    $this->response->send(true);

    //kill the entire script so nothing is processed past this point.
    exit;

For more information on the send method, check out the FuelPHP documentation for the response class.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top