2012-11-13 33 views

回答

6

有两种方法可以做到这一点。

一种方法是创建一个贡献莫过于并调用它在每一个控制器分派方法

Use onDispatch method in controller. 


    class IndexController extends AbstractActionController { 


     /** 
     * 
     * @param \Zend\Mvc\MvcEvent $e 
     * @return type 
     */ 
     public function onDispatch(MvcEvent $e) { 

      //Call your service here 

      return parent::onDispatch($e); 
     } 

     public function indexAction() { 
      return new ViewModel(); 
     } 

    } 

不要忘了,包括您的代码的顶部

use Zend\Mvc\MvcEvent; 

第二种方法是以下库通过Module.php使用调度事件执行此操作

namespace Application; 

use Zend\Mvc\ModuleRouteListener; 
use Zend\Mvc\MvcEvent; 

class Module { 

    public function onBootstrap(MvcEvent $e) {   
     $sharedEvents = $e->getApplication()->getEventManager()->getSharedManager(); 
     $sharedEvents->attach(__NAMESPACE__, 'dispatch', array($this, 'addViewVariables'), 201); 
    } 

    public function addViewVariables(Event $e) { 
     //your code goes here 
    } 

    // rest of the Module methods goes here... 
    //... 
    //... 
} 

How to create simple service using ZF2

reference2

reference3

+0

正如一个评论,这将是巨大的,如果你能缩短你的代码示例。发布一堆代码并自行找出所有东西只是很有用的。请解释你在做什么(我知道它,但问卷可能不会) – Sam

+0

谢谢山姆提醒我,如果你有足够的时间来回答它,只是麻烦回答一个问题。否则不要浪费时间来快速回答。我会记住这一点,只回答一个问题,如果我有足够的时间来彻底回答。 – Developer

+0

这么多的答案。我现在可以做到。 – user1820728

相关问题