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

Zend Framework:
Convert objects to arrays and back with zend-hydrator
Jun 21, 2017 @ 16:32:01

The Zend Framework blog has posted another in their series of component spotlights, focusing in on a single component of the framework and its use. In this latest article they cover the zend-hydrator component, useful for converting objects to arrays and back.

APIs are all the rage these days, and a tremendous number of them are being written in PHP. When APIs were first gaining popularity, this seemed like a match made in heaven: query the database, pass the results to json_encode(), and voilĂ ! API payload! In reverse, it's json_decode(), pass the data to the database, and done!

Modern day professional PHP, however, is skewing towards usage of value objects and entities, but we're still creating APIs. [...] Zend Framework's answer to that question is zend-hydrator. Hydrators can extract an associative array of data from an object, and hydrate an object from an associative array of data.

They start with the command to get the zend-hydrator package installed (and a dependency they'll need for their examples, zend-filter). A code example is included that shows how to convert a "book" object to an array using the ReflectionHydrator. Next is an example of switching it back, changing the array of data back into a book object. Next comes the integration with zend-filter, showing how to filter values out of objects/arrays you might not want in the end result by adding the filter to the hydrator. Also included are examples of modifying data (strategies), filtering on property names, delegation of the translation based on object type and a few other features included in the component that could be helpful.

tagged: zendframework component zendhydrator tutorial introduction filter translate

Link: https://framework.zend.com/blog/2017-06-21-zend-hydrator.html


Trending Topics: