如何在控制器的__construct()函数中退出没有die()的codeigniter?

I have a controller where in the constructor function, I want to check if the user is logged in or not. If not, I want an error message to be displayed, and for the script to exit without running any other function in the controller. This controller will only be called by ajax so the error would be displayed via JSON and then the javascript on the client will display it to the user.

How can I do this? If I did this:

function __construct()
{
   if (! $this->loggedIn() )
   {
      echo json_encode( array('error'=> true) );
      die;
   }    
}

I don't think the message would be displayed because codeigniter uses output buffering. Any ideas?

i understood that your problem is the client expects for a json type of response, so two options to use:

public function __construct(){

    $_bad_login_msg = 'please try again' ;
    parent::__construct();

    if(!userLoggedIn()){

        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($_bad_login_msg));

        //or just use 
        //     echo json_encode($_bad_login_msg);
        die;
    }
}

http://codeigniter.com/user_guide/libraries/output.html

you won't have any buffering problems, the buffer contents will be sent to the client after the die...

I'm pretty sure you can just use something like this:

function __construct()
{
   if (! $this->loggedIn() )
   {
     exit('Please login before visiting this page');
   }    
}

The best way is to redirect the user to login page. As mentioned here : https://stackoverflow.com/a/10399199/876117

public function __construct(){
  parent::__construct();
  if(!userLoggedIn())
    $this->load->view('promptlogin');
    $this->output->_display();
    exit();

}

public function index(){
  // one will never reach here unless he is logged in
  $this->load->view('actualcontent');
}

MY_Controller is your top level/parent controller so its all done in there because every other controller will extend it. So if you have an auth controller(which extends MY_Controller) you will have access to its logic.

So MY_Controller

class MY_Controller extends CI_Controller{

    protected $_user;

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

        $this->_user = $this->session->userdata('uid')
                     ? find_a_user : NULL;
        // if a session of user_id exists and is found in DB
        // we have a live user
    }
}

Auth

class Auth extends MY_Controller{
   public function __construct(){
        parent::__construct();
        // we now have access to $this->_user

        if($this->_user !== NULL)  // we have active user
    }
}

I think you should use flashdata and redirect to a controller with it. Then you can control if any flashdata comes in session, after that write it in view.