Constructor session validation for different functions

后端 未结 2 1276
广开言路
广开言路 2020-11-30 13:40

I\'m doing a validation in my constructor which checks whether the user has started a session.

I\'m then throwing in some controllers for various things.

My

2条回答
  •  醉梦人生
    2020-11-30 14:04

    What you need to do is set up a base controller that will look after the session for you and split your logged in controllers from your logged out ones via inheritance.

    My suggestion for you is to have a look at Phil Sturgeon's post on Keeping It Dry. In his post, Phil explains the basics on how to implement controllers in such a way that the parent controller will look after sessions so you don't have to check it every time.

    As an example:

    MY_Controller:

    class MY_Controller extends CI_Controller{
        function __construct(){
            parent::__construct();
            //do things in here that ALL controllers should do.
        }
    }
    

    MY_In_Controller:

    class MY_In_Controller extends MY_Controller{
        function __construct(){
            parent::__construct();
            //if user doesnt have the session redirect them out NOW!
        }
    }
    

    MY_Out_Controller:

    class MY_Out_Controller extends MY_Controller{
        function __construct(){
            parent::__construct();
            //if the user has the session, redirect them in NOW.
        }
    }
    

    Login Controller:

    class Login extends MY_Out_Controller{
        function __construct(){
            parent::__construct();
        }
    
        function index(){
            //folks that have a session (already logged in) will never even get here.
            //because the parent class MY_Out_Controller already redirected them back in.
        }
    }
    

    Manage Controller:

    class Manage extends MY_In_Controller{
        function __construct(){
            parent::__construct();
        }
    
        function index(){
            //folks that don't a session (logged out) will never even get here.
            //because the parent class MY_In_Controller already redirected them out.
        }
    }
    

    In short, don't write your session checks directly in controllers. You'll be writing it too often and violating the DRY Principle.

    Update: I recommend revamping Phil's method by using Shane Pearson's method in CodeIgniter's Base Classes Revisited.

提交回复
热议问题