2013-02-22 43 views
1

我正在使用spl_autoload進行依賴注入。PHP:我怎樣才能讓spl_autoload在全球範圍內的課堂上工作?

spl_autoload_register(function ($class) 
{ 
    $cFilePath = _CLASSLIB_ . "/class.$class.php"; 

    if(file_exists($cFilePath)) 
    { 
     include($cFilePath); 
    } 
    else 
    { 
     die("Unable to include the $class class."); 
    } 
}); 

這工作正常。但是,讓我們說的這些都是我的課:

class Test 
{ 
    public function foo() 
    { 
     echo "Here."; 
    } 
} 

而且

class OtherTest 
{ 
    public function bar() 
    { 
     global $Test; 

     $Test->foo(); 
    } 
} 

所以,在我執行代碼:

<?php 
$OT = new OtherTest(); //Dependency Injection works and loads the file. 
$OT->bar(); 
?> 

我會得到一個錯誤,因爲巴()嘗試測試類中的全局(未實例化,因此從未自動加載)。

除了在嘗試在每種方法中使用它之前檢查$ Test全局是否是對象之外,實現這一點的最佳方式是什麼?

回答

0

如果可能,請避免使用全局變量。您在評論中提到了依賴注入:您可以使用DI來解決此問題。

如果OtherTest依賴於Test的一個實例,那麼當它被構建時,該Test的這個實例應該被提供給OtherTest。

$T = new OtherTest($Test); 

你會明顯需要修改你的OtherTest類,以便測試實例作爲屬性,而這需要一個測試作爲參數構造函數,像這樣:

class OtherTest 
{ 

    protected $test = null; 

    public function __construct(Test $test) 
    { 
     $this->test = $test; 
    } 

    public function bar() 
    { 
     return $this->test->foo(); 
    } 

} 

你可以然後執行以下操作:

$test = new Test(); 
$otherTest = new OtherTest($test); 
$otherTest->bar(); 
+0

謝謝,克里斯!我最終完成的工作是設置構造函數,以便可以使用一組類名和對象作爲鍵/值對來重載它,通過switch語句運行它並將其分配給類中相應的受保護屬性。 – Tealstone 2013-02-22 20:24:45

0

我認爲你很困惑依賴注入是什麼意思。類自動加載不是依賴注入。依賴注入是實際注入對象可能具有的對象的依賴關係,以便它可以使用它。因此,接收依賴關係的對象與完全不需要創建它的依賴關係是分離的。

在這種情況下實現依賴注入的最好方法是將Test類的依賴注入到OtherTest實例化的OtherTest中。所以Othertest可能是這樣的:

class OtherTest 
{ 
    protected $test_object = NULL; 

    public function __construct($test_obj) { 
     if ($test_obj instanceof Test === false) { 
      throw new Exception('I need a Test object'); 
     } 
     $this->test_obj = $test_obj; 
    } 

    public function bar() 
    { 
     $this->$test_obj->foo(); 
    } 
} 

和代碼實例化可能看起來像:

$OT = new OtherTest(new Test()); // both OtherTest and Test would be autoloaded here if not previously loaded. 

注意,指的是一個未聲明的變量($Test在你的例子)是不會自動加載一個類,因爲變量名本身沒有類的上下文。你最終會因嘗試調用非對象的方法而出錯。

相關問題