Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

zend framework2 - How to pass variables to layout.phtml globally in ZF2?

I want to pass a series of variables to my layout.phtml throughout the whole application(globally). And by that I mean I don't wanna use

$this->layout()->someVar = someValue;

in each and every action I've got, since it would be a lot of extra work and code. So is there a way to do it in just one place? Or What I mentioned is all I got! Hope not :)

Maybe using sessions ? – Remi Thomas

Thanks for the solution. For the time being that's what I'm using. For logged-in user info, system and layout settings and an ACL list. But the problem is that I have to define a new object in the layout.phtml which I don't think is appropriate, is it? I read somewhere that whatever data we need to use in view models should be passed to it using controller actions. And specially I'm not a fan of cutting corners, so if there's a clean way to do this I'd rather not do it this way. And recently I have to get the number of unread messages for each user and use it in layout.phtml. So if I do it in layout.phtml it's a LOT of php script inside a view model or layout.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best and cleanest way is using a ViewHelper, as Orochi suggests. Here some instructions to create your own ViewHelper: http://framework.zend.com/manual/2.2/en/modules/zend.view.helpers.advanced-usage.html. It's not too complex ;)

However your problem could be resolved also in another way. Supposing the variables you need contain values provided by services already present in your application (and then exposed by ZF2 ServiceManager), you could add some lines on the "onBoostrap" function inside your Module.php (e.g. on Application module).

Here an example:

public function onBootstrap($e) {

    $serviceManager = $e->getApplication()->getServiceManager();
    $viewModel = $e->getApplication()->getMvcEvent()->getViewModel();

    $myService = $serviceManager->get('MyModuleServiceMyService');

    $viewModel->someVar = $myService->getSomeValue();

}

In this way you write the assignment in only one place. The variable is then accessible as usual:

$this->layout()->someVar;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...