Eric
Eric

Reputation: 2231

Codeigniter execute code in every controller

I'm rather new to Codeigniter, so I may be going about this the wrong way. In the header for my template, I have a spot for displaying account information or a message to log in.

In order for it to work properly, each controller obviously need to have the same code. To avoid this, the user guide says I should be able to extend CI_Controller and it automatically includes that code. However, that's not working for me. Here's what I've got.

application/core/MY_Controller.php:

<?php
class MY_Controller extends CI_Controller {
function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->model('user_model');

    if ( $this->user_model->validateToken ( $this->input->cookie('session_token', TRUE) ) ) 
    {
        $data['login_info'] = 'Logged in as '. $this->user_model->getUsernameAsLink($this->input->cookie('session_token', TRUE)).'<BR />
        <a href="/dashboard">Control Panel</a>';
    }
    else
    {
        $data['login_info'] = 'You are not logged in<BR />
        <a href="/account/login">Log In</a>';
    }      
}
}
?>

the model it references:

<?php
class User_model extends CI_Model {

public function __construct()
{

}

public function validateToken($token)
{
    // Get token from database to check against cookie
    $query = $this->db->query('SELECT `login_token` FROM `Users` WHERE `login_token` = "'.$token.'"');

    // Match Found?
    $rowCount = $query->num_rows();

    if ( $rowCount == 1 ) {
        return true;
    } else {
        return false;
    }
}

public function getUsernameAsLink ( $token )
{
    // Get token from database to check against cookie
    $query = $this->db->query('SELECT `username` FROM `Users` WHERE `login_token` = "'.$token.'"');

    foreach( $query->result() as $row ) {
        $username = $row->username;
    }

    $returnString = '<a href="/profile/'. $username .'">'.ucfirst ( $username ).'</a>';

    return $returnString;    
}
}
?>

I'm getting notice errors saying that the $data['login_info'] value doesn't exist. Is there anything I've left out to keep it from processing the extension to MY_Controller?

Upvotes: 0

Views: 2201

Answers (1)

CWSpear
CWSpear

Reputation: 3270

For $data to be available in your other controllers, you need to make it available. Try setting it to $this->data and using that same thing in the other controllers.

Upvotes: 1

Related Questions