I'm implementing the lazy initialization and dependency injection pattern in my PHP application at the moment and face the following question:
Every class has a bunch of getter and setter methods providing objects of foreign classes. Is there an elegant way to remove this "redundancy" to a parent class or some kind of factory?
EDIT: without loosing the advantages of testability ;-)
EDIT2: here is an example of a getter and setter method like I use them:
function getSql() {
if (is_object($this->sql) === FALSE) {
$registry = \Registry::getInstance();
$factories = $registry->get('factories');
$database = $factories['databaseSql'];
$this->sql = $database->getSql();
}
return $this->sql;
}
function setSql($sqlObject) {
// ... some checks
$this->sql = $sqlObject;
}
EDIT3 I followed the idea of using traits so here is a sample solution using a trait for the class "Registration":
trait Registration {
private $registration = null;
public function getRegistration() {
$registry = \Registry::getInstance();
$factories = $registry->get('factories');
if (is_object($this->registration) === TRUE) {
// get obect if instance already exists
$registration = $this->registration;
} else if (isset($factories['registration']) === TRUE) {
// get object using the matching factory
$registrationFactory = $factories['registration'];
$registration = $registrationFactory->getRegistration();
} else if (class_exists('\engine\classes\Registration') === TRUE) {
// get object using the default object class when no specific factory is defined
$registration = new \engine\classes\Registration();
} else {
throw new \Exception('error getting an instance of Registration');
}
$this->registration = $registration;
return $registration;
}
public function setRegistration($object) {
if (is_object($object) === FALSE)
throw new \Exception('invalid registration object');
$this->registration = $object;
}
}
Usage
class Foo {
use Registration;
public function bar() {
$reg = $this->getRegistration();
// ... use instance of Registration
}
}