Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2 - How to use the Hydrator/exchangeArray() to populate a nested object

I've got an object with values that are stored in my database. My object also contains another object which is stored in the database using just the ID of it (foreign key).

http://framework.zend.com/manual/2.0/en/modules/zend.stdlib.hydrator.html

Before the Hydrator/exchangeArray functionality in ZF2 you would use a Mapper to grab everything you need to create the object. Now I'm trying to eliminate this extra layer by just using Hydration/exchangeArray to populate my objects but am a bit stuck on creating the nested object.

Should my entity have the Inner object's table injected into it so I can create it if the ID of it is passed to my 'exchangeArray' ?

Here are example entities as an example.

// Village
id, name, position, square_id

// Map Square
id, name, type

Upon sending square_id to my Village's exchangeArray() function. It would get the mapTable and use hydrator to pull in the square using the ID I have.

It doesn't seem right to be to have mapper instances inside my entity as I thought they should be disconnected from anything but it's own entity specific parameters and functionality?

like image 644
Intellix Avatar asked Oct 06 '12 21:10

Intellix


1 Answers

I think you may benefit from looking at Zend\Stdlib\Hydrator\Strategy\StrategyInterface.

By creating a Strategy class you can attach this to your Hydrator, so when a specific key is found (square_id in this case) the Hydrator passes the data onto the Strategy class to either extract() or hydrate().

The Strategy class can then do whatever is required to hydrate and extract the data. I use a couple of Strategy classes that simply getArrayCopy()/exchangeArray() and other strategies that hydrate/extract multiple entities.

like image 112
DrBeza Avatar answered Oct 22 '22 17:10

DrBeza