2011-12-27 31 views
1

目前,我有一個主類Base加載所有其他控制器和模型,然後由Base加載的每個類具有類似的結構:

class SomeClass { 

    private $base; 

    function __construct(&$base) { 
     $this->base = $base; 
    } 

    function SomeMethod() { } 

} 

然後另一個類將不得不使用:

class AnotherClass { 

    private $base; 

    function __construct(&$base) { 
     $this->base = $base; 

     $this->base->SomeClass->SomeMethod(); 
    } 

} 

是否有訪問這些其他類的更好的辦法?

+0

你看過類SomeClass是否擴展了BaseClass? – 2011-12-27 16:20:31

+0

它們不擴展BaseClass的功能。它們由它加載,然後由BaseClass爲特定目的調用。 E.g. BaseClass可能會調用DatabaseClass和AuthenticationClass,然後調用一個使用AuthenticationClass和DatabaseClass的SomeController。 – jSherz 2011-12-27 16:21:10

+0

抱歉,看起來我沒有正確理解您的原始問題,請忽略我以前的評論。 – 2011-12-28 17:34:52

回答

1

也許是的someMethod()可以是靜態的:

class SomeClass { 

    private $base; 

    function __construct(&$base) { 
     $this->base = $base; 
    } 

    public static function SomeMethod() { } 

} 

然後就是:

class AnotherClass { 

    private $base; 

    function __construct(&$base) { 
     $this->base = $base; 

     SomeClass::SomeMethod(); 
    } 

} 
+0

感謝您的建議。這不適用於我必須使用這些類的每種情況,但是可以做幾種。 – jSherz 2011-12-28 09:41:14

1

聽起來像BaseFront Controller pattern的實現。前端控制器是Mediator的特例,它完全符合您的要求。它基本上允許SomeClassAnotherClass分開開發和維護,具有更少的依賴關係。

然而,而不是從Base類直接訪問類,它可能是最好有SomeClassAnotherClassBase類註冊自己,並揭露getter方法,其他對象調用:

class Base { 
    protected $_authenticator; 

    public function setAuthenticator(Authenticator $auth) { 
     $this->_authenticator = $auth; 
    } 

    public function getAuthenticator() { 
     return $this->_authenticator; 
    } 
} 

class Authenticator { 
    protected $_base; 

    public function __construct(Base $base) { 
     $this->_base = $base; 
     $this->_base->setAuthenticator($this); 
    } 
} 
+0

謝謝你的提示。我會去執行這個到我的項目。 – jSherz 2011-12-28 09:41:37