我開發與Zend框架2.一些應用服務通知其引發其他服務的一些方法有興趣的聽衆,例如應用程序:如何測試事件監聽Zend框架2 PHPUnit的
UserService
<?php
class UserService implements EventManagerAwareInterface
{
public function create($data = array())
{
// user is already created here
$params = array("user" => $user);
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, $params);
}
}
UserListener
<?php
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\EventInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class UserListener implements ListenerAggregateInterface
{
protected $serviceManager;
protected $listeners = array();
public function __construct(ServiceLocatorInterface $serviceManager)
{
$this->serviceManager = $serviceManager;
}
public function attach(EventManagerInterface $events)
{
$evm = $events->getSharedManager();
$this->listeners[] = $evm->attach('Application\Service\UserService', 'create.post', array($this, 'notify'));
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
public function notify(EventInterface $events)
{
$user = $events->getParam('user');
$mailService = $this->serviceManager->get('MailService');
$mailService->sendWelcomeMessage($user);
}
}
所以,我的問題是什麼是用PHPUnit測試Zend Framework事件監聽器的最佳做法,應如何正確測試所有監聽器方法附件(),detach(),notify()等等?
任何幫助將不勝感激!提前致謝!
我使用[samsonasik™]的幫助實現了Listener(https://samsonasik.wordpress.com/2013/05/18/zend-framework-2-register-event-listeners-in-configuration-file/) – m1st0
$ eventManager-> getListeners()將在版本3.0中刪除 – Hooli