Search code examples
phpcodeignitermodel-view-controllerhmvc

What is the right way to group my methods inside a single model?


I'm sorry for the title, maybe I couldn't describe it well. But here's what I want:

Now if I create a model m.php and put it inside the models folder with the following code:

class m extends CI_Model {

  public function username() {
    print "john doe";
  }

  public function password() {
    print "ABC123";
  }

}

Now, I can simply do the following in the controller :

$this->load->model("m");
$this->m->username(); // prints john doe
$this->m->password(); // prints ABC123

Now what I need to do is to make it in a way on which I can call the methds above as following:

$this->m->genralinfo->username(); // prints john doe

$this->m->privacy->password(); // prints "ABC123"

How can I achieve this ? I want to do this in order to group the methods that are specific to something alltogether, this helps me to structure my code better.

**I am aware that it is possible to create a new model for every group of methods but all I'd like to keep everything that is related to the user inside a single model **

Is this even possible using a single model ?


Solution

  • I think you want like this

    class m extends CI_Model
    {
        public $genralinfo;
        function __construct()
        {
            parent::__construct();
            $this->genralinfo=new Genralinfo();
        }
    
    }
    class Genralinfo
    //class Genralinfo extends CI_Model//you may extend CI_MODEL too
    {
        public function username() {
            print "john doe";
        }
    
        public function password() {
            print "ABC123";
        }
    
    }