Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

SitePoint PHP Blog:
Quick Tip: Convenience Hacks for Passing Data to Views
Aug 16, 2016 @ 16:09:38

On the SitePoint PHP Blog Reza Lavaryan has shared a "quick tip" about making it easier to pass data out to the views in your MVC application. It relates more specifically to when you have a lot of values to pass out rather than just a few bits of data.

In MVC based architectures, working with template engines is an inevitable part of the development routine. It usually goes like this: we prepare and pass the data to the view. In the view, we print them based on our layout design.

[...] There are times, however, when the number of variables might be much higher than this: ten or more. In that case, we’ll have a tall list of variables (as an associative array), being passed to the respective template. It gets messy and unreadable quickly. If only there was a way to just list what we need by name, and have PHP take care of the rest for us. Well… there is!

The example shows how to use the compact function built into PHP to grab values from the current scope and return them as an array. Unfortunately it does loose the array keys with this method, so they propose an alternative with the get_defined_vars function and some simple key handling to return a more correct version of the array.

tagged: quicktip hack data view compact getdefinedvars tutorial

Link: https://www.sitepoint.com/quick-tip-convenience-hacks-for-passing-data-to-views/


Trending Topics: