3
我執行我的PHP應用程序的延遲初始化和依賴注入模式的時刻,面臨着以下問題:多餘的getter和setter
每個類都有一堆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
}
}
我添加了一個例子,將通過你提到的鏈接閱讀。我知道繼承,魔術獲得者和二傳手。 – gro
當這個getter/setter對有一個特性用於每當另一個類需要這樣一個對象時,它會很好嗎? – gro