开发者

Codeigniter - make library run automatically

I have a lib like so

<?php if ( ! defined('BASEPATH')) e开发者_JAVA百科xit('No direct script access allowed');

class Iadmin {

    function check()
    {
        $CI =& get_instance();
        $CI->load->helper('url');
        $CI->load->helper('cookie');
        if(!get_cookie('lemon')){
            redirect('http://www.google.com/'); 
        }
    }
}

?>

In the autoload.php I have

$autoload['libraries'] = array('iadmin');

What I want to do: If I don't have cookie "lemon", I will be redirect to google when I try to access any page of my website

Problem: I'm not getting redirected to google.


You could extend the default controller with MY_Controller and then extend that in all your controllers.

In application/libraries/MY_Controller.php

<?php
    class MY_Controller extends Controller {
        function __construct(){
            parent::__construct();

            $this->load->helper('url');
            $this->load->helper('cookie');
            if(!get_cookie('lemon')){
                redirect('http://www.google.com/'); 
            }
        }
    }
?>

in application/controllers/home.php

<?php   
    class Home extends MY_Controller {
        function __construct(){
            parent::__construct();
        }

        function index(){
            // Index page
        }
    }
?>

Going to www.site.com/index.php/home would redirect you if you didn't have the lemon cookie.

You may also be able to do something like this with a hook, I'm not sure though as I've never used them.


You need to use Hooks in this situation, rather than libraries. Create a hook that runs before any of your controllers are loaded, and put your code to check for the cookie in the hook constructor.

Reference: http://codeigniter.com/user_guide/general/hooks.html


After adding the class in library you need to call the function Check() to make it execute or place that code in constructor.


Why don't you just put that code in the Iadmin class' constructor? That should fix your problem, the check method doesn't get called automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜