我目前正在我的 PHP 应用程序中实现延迟初始化和依赖注入模式,并面临以下问题:
每个类都有一堆提供外部类对象的 getter 和 setter 方法。有没有一种优雅的方法可以将这种“冗余”删除到父类或某种工厂?
编辑:不失去可测试性的优势;-)
EDIT2:这是一个 getter 和 setter 方法的示例,就像我使用它们一样:
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 我遵循了使用特征的想法,所以这里是一个使用“注册”类特征的示例解决方案:
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;
}
}
用法
class Foo {
use Registration;
public function bar() {
$reg = $this->getRegistration();
// ... use instance of Registration
}
}