2015-04-01 37 views
1

服务我有了一个构造函数,采用参数的PHP类:ZF2 - 我如何通过构造函数参数在Module.php

例如:

Users.php

namespace Forms; 
class Users 
{ 
    protected $userName; 
    protected $userProperties = array(); 

    public function __construct($userName, array $userProperties = null) 
    { 
    $this->userName = $userName; 
    $this->userProperties = $userProperties; 
    } 
    public function sayHello() 
    { 
    return 'Hello '.$this->userName; 
    } 
} 

现在,我想在这样一个模型文件使用这个类:

$form = new Forms\Users('frmUserForm', array(
      'method' => 'post', 
      'action' => '/dosomething', 
      'tableWidth' => '800px' 
      )); 

它工作得很好。但是,为了编写单元测试,我需要将其重构为Service Factory,以便我可以嘲笑它。

所以,我的服务工厂现在看起来是这样的:

public function getServiceConfig() 
    { 
     return array(
      'initializers' => array(
       function ($instance, $sm) 
       { 
        if ($instance instanceof ConfigAwareInterface) 
        { 
         $config = $sm->get('Config'); 
         $instance->setConfig($config[ 'appsettings' ]); 
        } 
       } 
      ), 
      'factories' => array(
       'Forms\Users' => function ($sm) 
       { 
        $users = new \Forms\Users(); 
        return $users; 
       }, 
      ) 
     ); 
    } 

有了这个重构的地方,我有两个问题:

  1. 如何使用窗体\用户服​​务示范考虑ServiceLocator的文件在模型文件中不可用?
  2. 如何在实例化模型中的Users类时更改Service Factory实例以为构造函数提供参数。

回答

2

我曾经遇到类似的问题。然后,我决定不向工厂传递参数。但建立setter方法来处理这个。

namespace Forms; 
class Users 
{ 
    protected $userName; 
    protected $userProperties = array(); 

    public function setUserName($userName) 
    { 
     $this->userName = $userName; 
    } 
    public function setUserProperties($userProperties) 
    { 
     $this->userProperties = $userProperties; 
    }   
    public function sayHello() 
    { 
     return 'Hello '.$this->userName; 
    } 
} 

你可以实现你的模型ServiceLocatorAwareInterface接口然后它可以调用下面的任何服务。

use Zend\ServiceManager\ServiceLocatorAwareInterface; 
use Zend\ServiceManager\ServiceLocatorInterface; 

class MyModel implements ServiceLocatorAwareInterface 
{ 
    protected $service_manager; 
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) 
    { 
     $this->service_manager = $serviceLocator; 
    } 

    public function getServiceLocator() 
    { 
     return $this->service_manager; 
    } 

    public function doTask($name, $properties) 
    { 
     $obj = $this->getServiceLocator('Forms\Users'); 
     $obj->setUserName($name); 
     $obj->setUserProperties($properties); 
    } 
}