2013-12-19 185 views
19

如何解决对可测试控制器的依赖性?具有相关性的可测试控制器

工作原理:一个URI被路由到一个控制器,一个控制器可能依赖于执行某个任务。

<?php 

require 'vendor/autoload.php'; 

/* 
* Registry 
* Singleton 
* Tight coupling 
* Testable? 
*/ 

$request = new Example\Http\Request(); 

Example\Dependency\Registry::getInstance()->set('request', $request); 

$controller = new Example\Controller\RegistryController(); 

$controller->indexAction(); 

/* 
* Service Locator 
* 
* Testable? Hard! 
* 
*/ 

$request = new Example\Http\Request(); 

$serviceLocator = new Example\Dependency\ServiceLocator(); 

$serviceLocator->set('request', $request); 

$controller = new Example\Controller\ServiceLocatorController($serviceLocator); 

$controller->indexAction(); 

/* 
* Poor Man 
* 
* Testable? Yes! 
* Pain in the ass to create with many dependencies, and how do we know specifically what dependencies a controller needs 
* during creation? 
* A solution is the Factory, but you would still need to manually add every dependencies a specific controller needs 
* etc. 
* 
*/ 

$request = new Example\Http\Request(); 

$controller = new Example\Controller\PoorManController($request); 

$controller->indexAction(); 

这是我的设计模式的例子解释

注册地:

  • 辛格尔顿
  • 紧耦合
  • 可测?没有

服务定位器

  • 可测?硬/否(?)

穷人迪

  • 可测试
  • 很难与很多依赖

注册表来维持

<?php 
namespace Example\Dependency; 

class Registry 
{ 
    protected $items; 

    public static function getInstance() 
    { 
     static $instance = null; 
     if (null === $instance) { 
      $instance = new static(); 
     } 

     return $instance; 
    } 

    public function set($name, $item) 
    { 
     $this->items[$name] = $item; 
    } 

    public function get($name) 
    { 
     return $this->items[$name]; 
    } 
} 

服务定位器

<?php 
namespace Example\Dependency; 

class ServiceLocator 
{ 
    protected $items; 

    public function set($name, $item) 
    { 
     $this->items[$name] = $item; 
    } 

    public function get($name) 
    { 
     return $this->items[$name]; 
    } 
} 

如何解决对可测试控制器的依赖关系?

+0

*“很难维护很多依赖项”* .. emm ..什么依赖关系? –

+0

你的控制器返回什么?你在测试什么?以什么方式? – mpm

回答

19

你在控制器中讨论的依赖关系是什么?

的主要解决办法是:

  • 使用DI容器通过构造
  • 注入工厂服务的控制器中的特定服务直接传递

我要去尝试分别详细描述两种方法。

注:所有的例子将