There are two ways to do this.
One way is to create a serice and call it in each controller dispatch method.
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(); } }
don't forget to include the following library on top of your code
use Zend\Mvc\MvcEvent;
The second way is to do it via Module.php using the send event
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) {
How to create a simple service using ZF2
reference2
reference3
source share