在Codeigiiter或其他MVC中处理不正确的方法(控制器)参数


Handling incorrect method (controller) parameters In Codeiginiter or other MVC

我在codeigitier中进行编码,但这个问题同样适用于任何MVC框架。

如何抽象逻辑,以确定控制器方法的参数在采用某些相同参数的多个方法中是否有效?

编辑:更多详细信息

例如,在我目前正在构建的应用程序中,有多个"站点",不同表中的几乎所有数据都属于一个站点,用户只能查看站点的子集。所以我的很多方法都启动method($site_id,...),所以如果我能有一个pre_controller钩子,它可以查看方法的参数,并检测参数中是否有$site_id,以及是否有权限检查,那就太好了。

问题是,并不是这些控制器中的所有方法都会有一个$site_id参数,所以我不能在CI_Controller 扩展的构造函数中自动进行检查

对于CodeIgniter来说,抽象逻辑的一种方法是创建一个超级类:

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        //...do stuff...
    }
    //...do stuff...
}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

所有想要共享相同逻辑的控制器都应该扩展MY_Controller,而不是CI_Controller

现在,在您的MY_Controller中,您可以创建函数来"处理多种方法中的错误参数"。

更新

您的控制器功能参数来自您的路线。例如mydomain.com/mycontroller/myfunction/param1/param2/将去往mycontroller public function myfunction($param1, $param2)

$site_id只是您的变量命名。你不能说出它的名字,即使你能,我也怀疑基于你如何命名变量的逻辑是个好主意。

一个简单的方法就是在每个需要验证函数的控制器的函数中显式调用验证函数(在基本控制器、库或辅助对象中存储一次),这样就可以进行精细的控制。

更新

Extending the controller would only work if my parameters were the same for each method. I'd like to detect automatically the parameters and perform checks. I suppose a call to a helper might be the best I can do, but Id just like to be able to completely abstract it away from the method. I suppose one option would be to have an array of which controllers and methods have $site_id as their first parameter and have a pre_controller hook to do the checking. But this would mean keeping the array up-to-date which kind of defeats the object of my question which is to make things as DRY as possible!

一般来说,为了获得自动化,你必须灵活地放弃并遵循惯例。所以不要走"使用助手"的方式,走自动检测的方式。。。创建自己的惯例。

在您的基本控制器中,使用$this->uri->segment(n)来检查是否存在某个URL模式,如果它存在,您是否知道site_id参数正在传入,并且您可以对其运行自动验证。

扩展相同的控制器,并在preDispatch或init方法中进行一些验证。

或者将验证抽象到控制器帮助程序中,并在两个控制器中使用它。