2013-02-22 66 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在你的例子)是不会自动加载一个类,因为变量名本身没有类的上下文。你最终会因尝试调用非对象的方法而出错。

相关问题