用zend 2的tableGateway进行插入 [英] Doing inserts with zend 2's tableGateway

查看:181
本文介绍了用zend 2的tableGateway进行插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用zf2的tableGateway,我不确定它导致的设计。

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

以下是如何使用zf2的tableGateway进行插入的典型示例从文档):

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;
    }
}

在我自己的项目中,我有一个约25属性(25列的表)。需要使用25个属性定义该类似乎是多余的,而且在实现tableGateway的类的方法中也将$ data数组写入每个属性的元素。我错过了什么吗?

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?

推荐答案

你可能想看看我的 QuickStart 101教程

基本上你可以做:

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
}

这篇关于用zend 2的tableGateway进行插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆