-1

in codeigniter I have my main controller:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller
{
    public function index()
    {
        $this->load->library('../controllers/forum');
        $obj = new $this->forum();
        $obj->test();
    }
}

And the controller I'm trying to access:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Forum extends CI_Controller
{
    function __construct()
    {
        echo "testing1";
        $this->load->library('session');
        parent::__construct();
        $this->load->database();
        $this->load->model('model_forum');
    }

    public function index(){

    }

    public function test(){
        echo "testing2";
        $this->data['forums'] = $this->model_forum->getForums();
        $this->load->view('homepage', $this->data);
    }
}

Everything is fine with my model_forum.php file, because it works if I put all the code in Main controller. But if I'm trying to access Forum controller, nothing works, only "testing1" echo goes through. Picture of error: PHP error

Anyone has any idea what I'm doing wrong? I'm new to PHP and codeigniter so I'm struggling a little bit. Thanks in advance.

Sparky
  • 98,165
  • 25
  • 199
  • 285
zlekonis
  • 31
  • 6

1 Answers1

0

You can't load a controller from a controller in CI - unless you use HMVC or something.

You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.

UPDATE

After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.

If this is the case, you'd get a cleaner solution by getting creative with your routes.

For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.

You can set up routes like this:

$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";

Then, you can call method 1 with a URL like http://example.com/method_1 and method 2 with http://example.com/method_2.

Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.


You could also go with remapping your controllers.

From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":

public function _remap($method)
{
    if ($method == 'some_method')
    {
        $this->$method();
    }
    else
    {
        $this->default_method();
    }
}