phpdatatablezend-framework2table-data-gateway

Doing inserts with zend 2's tableGateway


I using zf2's tableGateway and I'm unsure of the design it leads to.

Here is the canonical example of how to use zf2's tableGateway to do an insert (this from the docs):

public function saveAlbum(Album $album)
    {
        $data = array(
            'artist' => $album->artist,
            'title'  => $album->title,
        );

        $id = (int)$album->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getAlbum($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }

But defining the $data array seems redundant because I already have an Album class that looks like this:

class Album
{
    public $id;
    public $artist;
    public $title;

    public function exchangeArray($data)
    {
        $this->id     = (isset($data['id'])) ? $data['id'] : null;
        $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
        $this->title  = (isset($data['title'])) ? $data['title'] : null;
    }
}

In my own project I have a model with about 25 properties (a table with 25 columns). It seems redundant to have to define the class with 25 properties and than also write a $data array inside of the method of a class implementing tableGateway with an element for every one of those properites. Am I missing something?


Solution

  • You may want to take a look at my QuickStart 101 Tutorial.

    Basically you could do:

    saveAlbum(Album $albumObject) 
    {
        $hydrator   = new ClassMethods(false);
        $albumArray = $hydrator->extract($albumObject);
        // v-- not too sure if that one-liner works; normal if() in case it doesn't
        isset($albumArray['id']) ? unset($albumArray['id']) :; 
    
        // insert into tablegateway
    }