So I have a dispatch event listener in Module.php, that retrives user object from database, and sets layout variable with it. I want to access the very same object in controller. How can I pass it?
public function onBootstrap($e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$app = $e->getParam('application');
$app->getEventManager()->attach('dispatch', array($this, 'setPortfolioLayout'));
}
/**
* This event will set $user variable in layout when it's active
*
* @param MvcEvent $e
*/
public function setPortfolioLayout(MvcEvent $e)
{
$matchedRoute = $e->getRouteMatch();
if($matchedRoute->getParam('isPortfolio')) {
$em = $e->getApplication()->getServiceManager()->get('Doctrine\ORM\EntityManager'); /** @var ObjectManager $em */
$user = $em->getRepository('Application\Entity\User')->findOneBy(['login' => $matchedRoute->getParam('login')]);
if(! $user) {
$e->getResponse()->setStatusCode(404); return;
}
$viewModel = $e->getViewModel();
$viewModel->setVariable('user', $user);
$viewModel->setTemplate('layout/portfolio');
$matchedRoute->setParam('user', $user);
}
}
I've tried setting the RouteMatch parameter - not the best place to do it, and it is not visible in Controller.
There's a $e->getController()
method in listener. Should I add a special method for setting the user object for every controller that expects it (adding interfaces traits etc)?