📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Zend Framework / Laminas Models and TableGateway

Models and TableGateway

6 min read
Implement data access with TableGateway and ResultSet for clean model-database separation.

Models with TableGateway

namespace BlogModel;

use LaminasDbTableGatewayTableGatewayInterface;
use LaminasPaginatorAdapterDbSelect;
use LaminasPaginatorPaginator;

class Post {
    public int    $id;
    public string $title;
    public string $body;

    public function exchangeArray(array $data): void {
        $this->id    = $data["id"]    ?? 0;
        $this->title = $data["title"] ?? "";
        $this->body  = $data["body"]  ?? "";
    }

    public function toArray(): array {
        return ["id" => $this->id, "title" => $this->title, "body" => $this->body];
    }
}

class PostTable {
    public function __construct(private TableGatewayInterface $tableGateway) {}

    public function fetchAll(): Paginator {
        $select  = $this->tableGateway->getSql()->select();
        $adapter = new DbSelect($select, $this->tableGateway->getAdapter());
        return new Paginator($adapter);
    }

    public function getPost(int $id): Post {
        $rowset = $this->tableGateway->select(["id" => $id]);
        $row    = $rowset->current();
        if (!$row) throw new Exception("Could not find post $id");
        return $row;
    }

    public function savePost(Post $post): void {
        $data = $post->toArray();
        $id   = (int) $post->id;
        $id ? $this->tableGateway->update($data, ["id" => $id])
            : $this->tableGateway->insert($data);
    }

    public function deletePost(int $id): void {
        $this->tableGateway->delete(["id" => $id]);
    }
}