ba0708
ba0708

Reputation: 10599

Database access in Zend Framework 2

I want to find a good way to go about accessing my database from ZF2. I don't want to do this from my models or controllers and I don't want to use any ORM tools such as Doctrine (unless someone does a good job of convincing me!).

The tutorial application is using the Table Data Gateway pattern; it creates a class AlbumTable which accesses the album table in the database. I am concerned about this approach because I will be making a normalized database where I need to join several tables to represent some models. As far as I understand, this cannot be done with the TableGateway class. Sure, you could do $tblgateway->getSql() and go from there, but that kind of defeats the purpose of the Table Data Gateway pattern I think.

So, I turned my attention to Zend\Db\Sql\Sql. Building on the Album example, I got the following working:

class AlbumMapper {
    private $sql;

    public function __construct(Sql $sql) {
        $this->sql = $sql;
    }

    public function getAlbum($id) {
        $id = (int) $id;

        $select = $this->sql->select();
        $select->from('album');
        $select->where(array('id' => $id));

        $statement = $this->sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $row = $result->current();

        $album = null;

        if ($row) {
            $album = new Album();

            $album->setTitle($row['title']);
            $album->setArtist($row['artist']);
            $album->setId($row['id']);
        }

        return $album;
    }
}

The point here is that I could call $select->join() and join several tables, which would give me more control of querying my database and remove the 1:1 relationship between my models and the tables. However, if I do not need to join, then using the Table Data Gateway would surely save me from writing a bunch of code.

So, I guess my question is if a combination of the two approaches would be good depending on the situation? For instance, if I only need to access a single table (no joining with others), then I could use the Table Data Gateway, and if I need to join several tables, I could go with the other approach. Is this a good or bad idea? Are there any better alternatives?

Thank you in advance!

Upvotes: 1

Views: 1929

Answers (1)

Rob Allen
Rob Allen

Reputation: 12778

I use Mapper classes with Entity objects. To avoid writing too much repetitive code for the simple use-cases, I use ZfcBase's AbstractDbMapper to extends my specific mappers from.

Upvotes: 2

Related Questions