3

現在、PHP アプリケーションに遅延初期化と依存性注入パターンを実装しており、次の質問に直面しています。

すべてのクラスには、外部クラスのオブジェクトを提供する getter および setter メソッドが多数あります。この「冗長性」を親クラスまたはある種のファクトリに削除するエレガントな方法はありますか?

編集:テスト容易性の利点を失うことなく;-)

EDIT2:これは、私が使用するようなゲッターとセッターメソッドの例です:

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
    }
}
4

1 に答える 1

1

PHP言語のOOPの利点を知っていますか?

継承

特徴

魔法のゲッターとセッター

アスペクト指向プログラミングの可能性があります。たとえば、AOP を使用して PHP で再利用可能な流暢なインターフェイス パターンを実装します

たとえば、コードを提供しなかったため、非常に多くのリンクがあります。

于 2013-04-05T12:51:12.513 に答える