3
votes

I am using Zend Framework 2 and am having trouble trying to set up a variable to be used in the layout file.

Basically, I want to show the total number of items in a shopping cart in the navigation bar without having to load the value in all my controller actions.

From the research I have done so far, I have found out how to set up the variable in my module's onBootstrap, and how to print it in the layout.

I am using a third party module for the shopping cart, and my problem is that the value I want to set comes from a controller plugin, which works great when calling from my controllers, but have not found a way to call this plugin from onBootstrap.

What I am trying to do is:

public function onBootstrap(MvcEvent $e)
{
    $app = $e->getApplication();
    $events = $app->getEventManager();
    $shared = $events->getSharedManager();
    $sm = $app->getServiceManager();

    // Cart total items
    $total_items = $sm->get('ShoppingCart')->total_items(); // <-- Not working because it is declared as a controller plugin in the third party module
    $e->getViewModel()->setVariable('total_items', $total_items);
}

I was looking for some tips on how to achieve this, maybe there is a better way to do it.

Thanks in advance!

1

1 Answers

2
votes

To get a controller plugin, use this:

$plugins = $sm->get('ControllerPluginManager');
$plugin  = $plugins->get('ShoppingCart');

To set a variable, use this:

$events = $app->getEventManager();
$events->attach(
    MvcEvent::EVENT_RENDER,
    function($e) use ($plugin) {
        $viewModel = $e->getViewModel();
        $viewModel->totalItems = $plugin->totalItems();
    },
    100
);