Welcome Guest, Not a member yet? Register   Sign In
Check a function before doing anything?
#1

Hello,
I want to check a function (for example $this->auth->is_login()) before doing anything in controller?
Note:
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?
Reply
#2

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_

Code:
class N2_Controller extends CI_Controller {

    function __construct()
    {
        $this->auth->is_login();
        parent::__construct();
    }
}

and your other controllers :

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

class Child_controller extends N2_Controller {

    public function index(){

    }
...
ressan.ir
CI is nice Heart
Reply
#3

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.
Reply
#4

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') ) {
 
           redirect('/requests/login');
 
       }
 
   

See the docs for reference. Good luck.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB