Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding new library in CodeIgniter

I've just started learning CodeIgniter, and I'm following this authentication tutorial by nettuts+. I did not understand one thing in it:

He added the following constructor code in the Welcome controller, which basically can be accessed only if the Session has variable username, otherwise it will redirect to admin controller.

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

        if ( !isset($_SESSION['username'])){
            redirect('admin');      
        }       
    }

He said:

If you have multiple controllers, then instead of adding the above code in every controller, you should Create a new library, which extends the controller you will paste the code in, and autoload the library into project. That way this code runs always when a controller is loaded.

Does it mean, I should

  1. Create a file in application/libraries (eg. auth.php)
  2. Paste this code in the auth.php

.

if ( !isset($_SESSION['username'])){
            redirect('admin');      
        }

Now how to autoload this library and make it run every time a controller is loaded as he said? Thanks

like image 726
Roman Avatar asked May 28 '11 08:05

Roman


1 Answers

1) to autoload a library, just add it to the array in the file application/config/autoload.php, look for the 'library' section and paste the name of the library(without extension) there, as an element of the array.

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

2) I suggest you use the native session handler (session library), which works pretty well and avoids you to use php $_SESSION. You set a width $this->session->set_userdata(array('username' => 'User1', 'logged' => 'true'), and then you retrieve the values with $this->session->userdata['logged'], for ex.

Works like a charm and don't have to call session_start() and so on. Go check the help because it's really really clear on that.

3) As for your problem, I'll go, instead, for 'hooks'. There are different hooks, depending on their 'position', i.e. the moment in which you're calling them.

You can use, for ex.. the 'post_controller_constructor', which is called after controller initialization but BEFORE the methods, so it's in a midway between the constructor and the actual method. I usually insert this controls here.

You define hooks in application/config/hooks.php, and give them an array:

   $hook['post_controller_constructor'] = array(
      'class'    => 'Auth',
       'function' => 'check',
       'filename' => 'auth.php',
        filepath' => 'hooks',
        'params'   => array()
    );

Anyway, for all these needs, the docs are pretty clear and straightforward, I suggest you read about hooks and session and you'll see everything gets much clearer!

like image 120
Damien Pirsy Avatar answered Oct 20 '22 08:10

Damien Pirsy