简体   繁体   中英

Should I call redirect() from within my Controller or Model in an MVC framework?

I'm using the MVC PHP framework Codeigniter and I have a straight forward question about where to call redirect() from: Controller or Model?

Scenario:
A user navigates to www.example.com/item/555. In my Model I search the item database for an item with the ID of 555. If I find the item, I'll return the result to my controller. However, if an item is not found, I want to redirect the user somewhere. Should this call to redirect() come from inside the model or the controller? Why?

No your model should return false and you should check in your controller like so:

class SampleModel extends Model
{
    //Construct

    public function FetchItem($id)
    {
        $result = $this->db->select("*")->from("table")->where("item_id",$id)->get();
        if($result->num_rows() == 0)
        {
             return false;
        }
        //return result
    }
}

and within your controller do:

function item($id)
{
     $Item = $this->SampleModel->FetchItem($id);

     if(!$Item)
     {
          redirect("class/error/no_item");
     }
}

Models are for data only either return a standard result such as an key/value object or a boolean.

all logic should be handled / controlled by the Controller.

Models are not page specific, and are used globally throughout the whole application, so if another class / method uses the model, it might get redirect to the incorrect location as its a different part of your site.

It seems like the controller would be the best place to invoke your redirect because the controller typically delegates calls to the model, view, or in your case, another controller.

However, you should use whatever makes the most sense for your application and for what will be easier to maintain in the future, but also consider that rules do exist for a reason.

In short, if a coworker were to try to fix a bug in your code, what would the "reasonable person" standard say? Where would most of them be most likely to look for your redirect?

Plus, you said you're returning the result to your controller already... perhaps that's where you should make your redirect...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM