我有一个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'
) );
它工作正常。但是,为了编写单元测试,我需要将其重构为服务工厂,以便对其进行模拟。
因此,我的服务工厂现在看起来像这样:
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;
},
)
);
}
完成此重构后,我有两个问题:
我有一段时间遇到类似的问题。然后,我决定不将参数传递给Factory本身。但是建立类似这样的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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句