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

為{幸葍}努か 提交于 2019-12-10 20:23:35

问题


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?


回答1:


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.




回答2:


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...



来源:https://stackoverflow.com/questions/4601460/should-i-call-redirect-from-within-my-controller-or-model-in-an-mvc-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!