2012-11-13 32 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

相關問題