Sending an Object to All Views and Accessing it in Your Layout in Zend Framework 2
In all of my Zend Framework applications that have user logins I like to display if the user is logged in and provide a link to login or logout depending on their current state. In Zend Framework 1 it was easy, I would define a function that would get called at the start of every action (_initView()
) and then it would be easy to set any variables that needed to be set on every page.
Then in the layout.phtml file you can easily access the variable like so.
In Zend Framework 2 it isn't as easy.
The first problem is that instead of setting view variables through the view object you need to return a ViewModel object from the Controller. The example in the Quick Start shows creating a new ViewModel and passing an array of the variables that you are going to pass. However, there isn't anything saying you can't create the ViewModel in advance and then return it at the end of your actions.
That way you don't have to manually set every layout wide variable every time you create an action.
The nice thing about ZF2 is that it's even easier to access the variables you pass in the views but in the layouts it's not as simple. It turns out you have to go through an additional step in order to access them.
I'm still in the starting phase of my ZF2 application but it seems like a good update after you get past the namespaces and all the changes...
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows