Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Hybrid Controller - way to decide wich action to fire
  • Hello, what would be the way to determine, which action (normal or restful) to call within a hybrid controller?

    Consider this:

    //GET via controller/stats
    public function action_stats($params) { //logic ... }

    //AJAX GET controller/stats
    public function function get_stats($params) {  if( $this->is_restful() ) { //AJAX logic... }  }


    or this one ...
    //if GET -> show form. if POST -> validate and save
    public function action_createreview($params)
       if(\Input::method() === 'POST') 
       { 
        //saving the form data 
       }
       else
       {
        //show the form ....
       }

    }

    public function post_createreview($params)
    {
    if( $this->is_restful() )
    {
    //AJAX logic ...
    return->response($returnDataArray) //will be returned as JSON, since jQuery set 'dataType' to 'json'  
    }
    }

    I know it isn't a best practice by combining RESTful logic with a "standard" way, but get_stats() will be primary called via AJAX from the browser and the response isn't always a JSON data. Sometimes it is a already rendered HTML-View 
  • If your action only ever does one thing, it's fine to call it "action_methodname".

    If it does multiple things (which whould require you to check the method for both GET and POST for example) I would split it in a "get_methodname" and a "post_methodname". For simplification, and also because it's not exactly best practice to have a method do multiple things...

    Either way, you need to check if it's a RESTful call if you want to extract JSON data, since method based routing works for browser requests too.
  • alright, so the solution would be something like this:

    public function get_login()
    {
       //just show the form...
    }

    public function post_login()
    {
       if( ! $this->is_restful() )
       {
          //handle regular login a.k,a oldschool-way 
       }
       else
       {
    //handle AJAX-Login an return some JSON response.....
       }
    }

    right ?
  • HarroHarro
    Accepted Answer
    If you want something truly hybrid, and you want to re-use the same action name (login in this case) for two different "actions" (showing a form and processing it's data), then yes.

    You have to think about how you are going to repopulate the form in case the POST validatio fails (you would not want to present the user with an empty form again in must cases, and you would want to display error messages, possibly per field.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion