CodeIgniter: loading multiple models in the same controller

codeigniter

I searched the whole Internet and either there is no one mentioning my problem, or I'm stupid, or maybe it's just a bad day for coding.

What's the situation:

  • controller "source"
  • model "source"
  • model "login"

The "login" model is loaded from autoload.php, then in each controller's constructor I have $this->login->check(), which is checking if the user is logged in (obviously). Then in some of the methods I'm using the "source" model to connect to the database.

I tried loading both of the models from the autoload array, I also tried to load them in the way described here, but it's obviously for an old CI version (the thread is from 2008) and I tried all the possible ways I had in my mind.

Anyway, the result is this:

A PHP Error was encountered

Severity: Notice

Message: Undefined property: Source::$login

Filename: controllers/source.php

Line Number: 10

Fatal error: Call to a member function check() on a non-object in …\application\controllers\source.php on line 10

Any ideas what I'm missing or how to fix it…? I'm stuck for hours and I don't have any ideas what I could do…

Edit 1: here is the code from the "source" controller:

class Source extends CI_Controller {

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

      $this->load->model('login');

      $this->login->check();
  }

  function index() {
      // Pagination config, getting records from DB

      $this->load->view('templates/layout', $data);
  }

  function add() {
      $this->load->model('source', '', true);

      $btn = $this->input->post('btn');

      if(isset($btn)) {
          // More form validation

          if($this->form_validation->run() == TRUE) {
              if($btn == "Add") {
                  // here I am supposed to use the source model...
              }
          }
      }

      $data['page'] = 'source_add';

      $this->load->view('templates/layout', $data);
   }

 }

?>

Edit 2: login.php:

<?php

class Login extends CI_Model {

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

  function authenticate($username, $password) {
      // the login script comes here
  }

  function logged() {
      if($this->session->userdata('logged') == true) {
          return true;
      } else return false;
  }

  function check() {
      if(!$this->logged()) {
          redirect('/authentication');
      }
    }
  }
?>

Best Answer

Conventionally, the classname of Models should end with _model, so it not collides with controllers with the same name, so try changing

class Login extends CI_Model {

to

class Login_model extends CI_Model {
Related Topic