2015-04-01 32 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); 
    } 
}