Question

I have the Module_One in which function exampleOne()...

class Model_One extends CI_Model {

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

    function exampleOne(){
        return "test";
    }
}

I wonder how, (if that is possible), call the Model_One within Model_Two...

class Model_Two extends CI_Model {

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

    function exampleTwo(){
        return "testTwo";
    }
}

In a way that I could just call the Model_Two and use the exampleOne() of Model_One.

class Controller_One extends CI_Controller{

    function index(){
        $this->load->model('Model_Two');
        $this->Model_Two->exampleOne();
    }
}









I know I could do it that way ...

class Model_One extends CI_Model {

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

    function exampleOne(){
        return "test";
    }
}

and so ...

class Model_Two extends CI_Model {

    function __construct()
    {
        parent::__construct();
        $this->load->model('Model_One');
    }

    function exampleTwo(){
        return "testTwo";
    }

    function exampleOne2(){         
        $this->Model_One->exampleOne();
    }
}

and so ...

class Controller_One extends CI_Controller{

    function index(){
        $this->load->model('Model_Two');
        $this->Model_Two->exampleOne2();
    }
}



However, redundant create a function to call another function, I know it must have another way to do this, but I do not know, and found nothing upon. anyone any ideas?

Thanks for your attention

Was it helpful?

Solution

yeah, Programming should DRY (Dont Repeat Yourself).

for your case, try this code :

class Model_Two extends CI_Model {

    function __construct()
    {
        parent::__construct();
        $this->load->model('Model_One');
    }

    function exampleTwo(){
        return "testTwo";
    }

    // change this method to the name of the another module
    function model_one(){

        // just return the new model object
        // so you can keep using all method in this object, without repeat the methods
        return $this->Model_One;
    }
}

and in your controller, you use the model_two model like this :

class Controller_One extends CI_Controller{

    function index(){
        $this->load->model('Model_Two');
        $this->Model_Two->model_one()->exampleOne();

        // and here you can use all method from model_one...
        // $this->Model_Two->model_one()->exampleTwo();
    }
}

I hope this help for you. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top