I have recently started to work on creating a MVC PHP private framework (I know, there is no classical MVC in PHP, you guys understand what I mean by MVC in PHP).
I have encountered a problem, I know that a single controller can load multiple models for specific tasks. That's ok, but what happens when my models should load the same libraries/dependencies? Eg:
<?php
abstract class Model {
protected $db = null;
protected $validator = null;
protected $validations = null;
protected function _startDb() {
if ( $this->db === null ) {
$this->db = new Db();
}
}
protected function _startValidator() {
if ( $this->validator === null ) {
$this->validator = new Validator();
}
}
protected function _startValidations() {
if ( $this->validations === null ) {
self::_startValidator();
$this->validations = new Validations($this->validator);
}
}
// I have more functions like these, as you can see, they load needed libraries.
}
// Now my models which they all need some of these libraries that are loaded in model class.
class Roles extendes Model {
public function getRoles() {
// Makes use of _startDb(), _startValidations()...
}
}
class Permissions extends Model {
public functoin getPermissions() {
// Also makes use of _startDb(), _startValidations()...
}
}
Well, I find no problem with this code as long as my controller just load one model. But it's not clear to me, and this is what bothers me, if I load multiple models in one controller, then it means that each model have its own instance of each library.
I do not like that, because specially db queries will get slower.
So my question, what is the best way to keep things well organized and have one instance of each library and share them among multiple models.
Btw, I know about dependency injection, but some models would need to get like 4 libraries and thats feels wrong to me. And then I feel like the controller would have load all the libraries, and I do not know if thats ok.