0

I am trying to get the php class Base to load only once for a custom MVC framework. So that i can close the database connection in the destructor and be able to use it in inheritance but I can't seem to figure it out. I looked at a singleton design here but i cant figure out how to load the database. Is there a way to get this working or perhaps a better way to do this. Or am i going about this in a totally stupid way and should change it?

Base class

class Base {
    protected $db;
    //constructor
    public function Base(){
        echo some unique id to test it worked
        $db = connection to database
    }

    //load modules as needed
    public function load($m){
        $this->$m = new $m;
    }
}

module class

class module extends Base {
    //some random function
    public function listing(){
        $this->db->query();
    }
}

the index.php which initializes the Base class

 $main = new Base;
 $main->load( 'module' );
 $main->module->listing();
tereško
  • 58,060
  • 25
  • 98
  • 150
spy-killer
  • 405
  • 4
  • 18
  • 3
    You should use an inversion of control (IoC) container instead of this. Check https://stackoverflow.com/questions/18562752/understanding-ioc-containers-and-dependency-injection – apokryfos Feb 04 '18 at 09:44
  • 1
    You could also use a simple registry pattern and inject that into your classes, then you have single place to get/set your objects. https://3v4l.org/r1YkR – Lawrence Cherone Feb 04 '18 at 10:10
  • The main mistake you are making is "using codeigniter as example". That's a terrible idea, which has lead you to using anti-patterns. – tereško Feb 04 '18 at 11:23
  • Thank you apokryfos and Lawrence I was able to reconstruct my code to follow this pattern which resolved a lot of my headaches. – spy-killer Feb 05 '18 at 03:17

0 Answers0