3

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!

4

1 回答 1

2

要获取控制器插件,请使用以下命令:

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

要设置变量,请使用:

$events = $app->getEventManager();
$events->attach(
    MvcEvent::EVENT_RENDER,
    function($e) use ($plugin) {
        $viewModel = $e->getViewModel();
        $viewModel->totalItems = $plugin->totalItems();
    },
    100
);
于 2013-11-05T21:31:17.927 回答