Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Assumption:

  • table: album
  • columns: id, data
<?php

include 'vendor/autoload.php';

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Predicate\Expression;
use Zend\Db\ResultSet\HydratingResultSet;

$adapter = new Adapter(array(
   'driver'   => 'pdo_pgsql',
   'database' => 'learn',
   'username' => 'developer',
   'password' => '123456'
));

$objectPrototype = new class extends \ArrayObject {

    public function __construct()
    {
        parent::__construct([], parent::ARRAY_AS_PROPS);
    }

    public function exchangeArray($data)
    {
        $prefix = 'album.';
        foreach ($data as $key => $value) {
            $replace = $prefix . $key;
            $this->$replace = $value;
        }
    }
};

$resultSetPrototype = new HydratingResultSet(
    null,
    $objectPrototype
);

$tableGateway = new TableGateway('album', $adapter, null, $resultSetPrototype);
$select = $tableGateway->getSql()->select();
var_dump(
    $tableGateway->selectWith($select)->toArray()
);
?>

result:

array(2) {
  [0] =>
  array(2) {
    'album.id' =>
    int(1)
    'album.data' =>
    string(38) "album data 1"
  }
  [1] =>
  array(2) {
    'album.id' =>
    int(2)
    'album.data' =>
    string(53) "album data 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment