CodeIgniter Forums

Full Version: Check a function before doing anything?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to check a function (for example $this->auth->is_login()) before doing anything in controller?
1- I check it in any control
2- If false goto login else view page.

How can I have this without code in my controllers?
i think you can do this :
- create a controller in /core/ that extends CI_Controller and call your function in constructor function of that class,
- your other controllers must extend your controller class,

example , i use this base class for my project, notice you must use MY_ (or any that you set in config) instead of N2_

class N2_Controller extends CI_Controller {

    function __construct()

and your other controllers :

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

class Child_controller extends N2_Controller {

    public function index(){

Do you want to check if a function exists or if the result of your function exists ? I say that because your example looks like checking if $this->auth->is_login() == TRUE.
If you want to check if a method in a class exists, you can use method_exists() or is_callable().
Be careful : method_exists() will return true (or false) for a private/public/protected method whereas is_callable() returns true (or false) for only public method in a class and all method like __call.
I used a 'post_controller_constructor' hook to do this:

Hook in config/hooks.php:
PHP Code:
$hook['post_controller_constructor'] = array(
   'class'     => 'Auth',
   'function'  => 'check',
   'filename'  => 'Auth.php',
   'filepath'  => 'hooks',

Check Function in hooks/Auth.php:
PHP Code:
   public function check()
       // get the current controller and method from the url
       $controller     $this->CI->uri->segment(1,'none');
       $method         $this->CI->uri->segment(2,'none');

       // if the user is not logged in && the request is not requests or login
       if ((!$this->CI->User->isLoggedIn) && ($controller != 'requests') && ($method != 'login') ) {

See the docs for reference. Good luck.