基本控制器并将其应用于所有现有控制器 [英] base controller and apply it to all existing controller

查看:82
本文介绍了基本控制器并将其应用于所有现有控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to create codeigniter base controller to check allowed ip address in database by mobel function if the ip is exists then user should go to home page but if the ip address is not exists and show 404 page in codeigniter, i can't find core folder in application folder

推荐答案

首先,您需要扩展一个核心类,将其命名为 MY_Controller.php

First, you need to extend a core class, call it 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 ,它将验证用户是否具有访问权限。这相对简单,我不会在此显示任何示例。

Now, we're assuming you have a model called ip_table_model which connects to database with list of IP addresses, and there's a function called check_ip which will validate whether user has access or not. This is relatively simple, and I won't show any examples on this.

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

The redirect('error_404'); page does not yet exist, you need to create a controller which shows your 404 page.

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

Now, for any other controllers in your project, instead of extends CI_Controller, make them extend MY_Controller instead.

示例:

class Welcome extends MY_Controller {

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

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

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

Explanation: We're extending CI_Controller to create our own core controller, called MY_Controller. Inside, we're checking if user has access or not through the constructor, which will be called in every other controller in the project.

参考文献:

http://codeigniter.com/user_guide/libraries/input.html

这篇关于基本控制器并将其应用于所有现有控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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