Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter HMVC extends MX_Controller, unable to use get_instance properly

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?

like image 210
goFrendiAsgard Avatar asked Sep 25 '12 15:09

goFrendiAsgard


2 Answers

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;
like image 81
PK. Avatar answered Nov 01 '22 11:11

PK.


I had the same problem, found that post and it made my website work, give it a try maybe?

"You don’t need to extend MX_Controller unless you are planning on running a controller within another controller. In alot of cases the code be put into a library. Otherwise, your controller should just extend MY_Controller."

Found here: http://ellislab.com/forums/viewthread/179478/

like image 31
NaturalBornCamper Avatar answered Nov 01 '22 10:11

NaturalBornCamper