0

zf2 の tableGateway を使用していますが、それがもたらす設計がわかりません。

zf2 の tableGateway を使用して挿入を行う方法の標準的な例を次に示します (これは 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');
            }
        }
    }

しかし、次のような Album クラスが既にあるため、 $data 配列を定義するのは冗長に思えます。

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 配列を記述する必要があるのは冗長に思えます。何か不足していますか?

4

2 に答える 2

2

もう 1 つの方法は、RowGateway http://framework.zend.com/manual/2.3/en/modules/zend.db.row-gateway.htmlを使用することです。

簡単に言えば、 \Zend\Db\RowGateway\AbstractRowGateway クラスからアルバム クラスを拡張します。

<?php
namespace Module\Model;

use Zend\Db\RowGateway\AbstractRowGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;

class Album extends AbstractRowGateway
{
    protected $primaryKeyColumn = array( 'id' );
    protected $table = 'album';


    public function __construct( Adapter $adapter )
    {
        $this->sql = new Sql( $adapter, $this->table );
        $this->initialize();
    }

}

そして、あなたはこのようにすることができます

$album->title = "Some title";
$album->save();

または

$album->populate( $dataArray )->save();
于 2014-04-24T13:42:21.137 に答える
1

私のQuickStart 101 Tutorialをご覧になることをお勧めします。

基本的に、次のことができます。

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
}
于 2014-04-23T19:39:11.927 に答える