fuelphpfuelphp-routing

Interrupt FuelPHP REST controller flow and display response


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

Solution

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