基本控制器并将其应用于所有现有控制器

时间:2012-01-06 10:05:42

标签: codeigniter

我需要创建codeigniter基本控制器,通过mobel函数检查数据库中允许的ip地址,如果ip存在则用户应该转到主页,但如果ip地址不存在并且在codeigniter中显示404页面,我可以'找到应用程序文件夹中的核心文件夹

4 个答案:

答案 0 :(得分:5)

首先,你需要扩展一个核心类,称之为 MY_Controller.php

将该文件保存在: application / core / MY_Controller.php

class MY_Controller extends CI_Controller {
    function __construct()
    {
        parent::__construct();

        $this->load->model('ip_table_model');
        $this->load->library('input');

        // assuming there's a function called "check_ip($ip_address)" in ip_table_model
        if (!$this->ip_table_model->check_ip($this->input->ip_address()) {
             redirect('error_404');
        }
    }    
}

现在,我们假设您有一个名为 ip_table_model 的模型,它连接到具有IP地址列表的数据库,并且有一个名为 check_ip 的函数,它将验证用户是否是否有权访问。这个相对简单,我不会在此展示任何例子。

redirect('error_404');页面尚不存在,您需要创建一个显示404页面的控制器。

现在,对于项目中的任何其他控制器,而不是扩展 CI_Controller ,使它们扩展为 MY_Controller

以下是一个例子:

class Welcome extends MY_Controller {

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        $this->load->view('welcome_message');
    }
}

说明:我们正在扩展 CI_Controller 来创建我们自己的核心控制器,名为 MY_Controller 。在内部,我们正在检查用户是否可以访问构造函数,该构造函数将在项目中的每个其他控制器中调用。

<强>参考文献:

答案 1 :(得分:1)

答案是here扩展核心类部分)。

1.7.2与2.0。*的结构不同,因此应用程序中没有 core 文件夹

答案 2 :(得分:1)

在Core中创建一个新类。 名称MY_Controller.php

class MY_Controller extends CI_Controller {
 // Write your functions here which you wanna use throughout the website
public function abc (){
  echo "Helllo";

}
}


class Welcome extends MY_Controller {

        function __construct()
        {
            parent::__construct();
        }

        function your_custom_fuctions()
        {

            $this->abc(); //echo Hello...
 //Anything you want to do
        }
}

答案 3 :(得分:0)

function admin_view($view_name = "", $header_info = NULL, $sidebar_info=NULL,$page_info = NULL, $footer_info = NULL, $data_info = ""){

    $this->load->view('Admin/includes/header', $header_info);
    $this->load->view('Admin/includes/Left_sidebar', $sidebar_info);
    $this->load->view($view_name, $page_info);
    $this->load->view('common/footer', $footer_info);
}
相关问题