CodeIgniter HMVC extends MX_Controller, unable to use get_instance properly

goFrendiAsgard picture goFrendiAsgard · Sep 25, 2012 · Viewed 13.7k times · Source

I have a controller in /application/core

/application/core/CMS_Controller.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require APPPATH."third_party/MX/Controller.php";

class CMS_Controller extends MX_Controller {

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

    public function show_something() {
        echo "something shown";
    }
} 

I have another controller in a module (/modules/my_module/controllers/controller.php) which extended from CMS_Controller

/modules/my_module/controllers/controller.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Controller extends CMS_Controller {

    public function index() {
        $this->load->view('view');
    }
} 

And, in view.php (/modules/my_module/views/view.php) I do this: /modules/my_module/views/view.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 $ci =& get_instance();
 echo $ci->show_something();
?> 

And I get this error:

Fatal error: Call to undefined method CI::show_something() in /home/gofrendi/public_html/No-CMS/modules/my_module/views/view.php on line 3

It will works if I don’t use MX_Controller and using CI_Controller instead: /application/core/CMS_Controller.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//require APPPATH."third_party/MX/Controller.php";

class CMS_Controller extends CI_Controller {

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

    public function show_something() {
        echo "something shown";
    }
} 

Anybody know what’s wrong here?

Answer

PK. picture PK. · Jul 22, 2013

In application/third_party/MX/Controller.php at the end of the constructor (after line 54) i added

/* allow CI_Controller to reference MX_Controller */
CI::$APP->controller = $this;

if you look at the code $this refers to the current class which is MX_Controller and CI::$APP refers to the CI_controller (look at the MX/Base.php file)

so now its simple... to get the reference to CI_Controller we will do (as per normal)

    $this->CI =& get_instance();

and to get reference to MX_Controller we will do

    $this->CI =& get_instance()->controller;