CodeIgniter global function

2019-02-13 03:55发布

问题:

Where can I place my "global" function, which will check, if user is logged in?

Because I want to do something like: user is able to browse some pages only when the function isLogged() returns TRUE, and I'd have to use it in some views, that's why it should be a "global" function, which I can access from anywhere.

Is that possible? Or there is any better solution for this?

回答1:

You should probably put it into a Library, and autoload the library. When you need to use the "logged_in" flag in a view, pass it in from the controller. Example:


application/libraries/Auth.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Auth
{

    public function is_logged_in ()
    {
        // Change this to your actual "am I logged in?" logic
        return $_SESSION['logged_in'];
    }

}

application/config/autoload.php

...
$autoload['libraries'] = array(
    ...
    'auth',
    ...
}

`application/controllers/welcome.php

<?php ...

public function index ()
{
    $view_data = array
    (
        'logged_in' => $this->Auth->logged_in()
    );
    $this->load->view('my_view', $view_data);
}

application/views/my_view.php

<? echo $logged_in ? 'Welcome back!' : 'Go login!' ?>


回答2:

Are you using an authentication library? If not I'd suggest one. They come with functions like that.

Tank Auth for example has: is_logged_in() , which does exactly what you want!

http://www.konyukhov.com/soft/tank_auth/

For more info about which library to use you should check out this answer which compares all libs: https://stackoverflow.com/a/476902/576223

If you don't want an authentication library you can do as suggested by Joe



回答3:

you can use MY_controller with all function needed on every page of your website. and inherit all controllers from it. read this oficial wiki