我应该从MVC框架的Controller或Model内部调用redirect()吗? [英] Should I call redirect() from within my Controller or Model in an MVC framework?

查看:91
本文介绍了我应该从MVC框架的Controller或Model内部调用redirect()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC PHP框架Codeigniter,并且有一个直接的问题,关于从哪里调用redirect():Controller或Model?

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

场景:
用户导航到www.example.com/item/555.在我的模型中,我在项目数据库中搜索ID为555的项目.如果找到该项目,则将结果返回给控制器.但是,如果找不到项目,我想将用户重定向到某个地方.这个对redirect()的调用应该来自模型内部还是控制器内部?为什么?

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?

推荐答案

没有模型应返回false,而应按以下方式检入控制器:

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.

所有逻辑均应由控制器处理/控制.

模型不是特定于页面的,而是在整个应用程序中全局使用,因此,如果另一个类/方法使用该模型,则它可能会重定向到错误的位置,因为它是您网站的不同部分.

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.

这篇关于我应该从MVC框架的Controller或Model内部调用redirect()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆