Skip to content

Instantly share code, notes, and snippets.

@samsonasik
Last active October 5, 2017 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsonasik/35d3d4d053586d1ddfe9295c9152cc62 to your computer and use it in GitHub Desktop.
Save samsonasik/35d3d4d053586d1ddfe9295c9152cc62 to your computer and use it in GitHub Desktop.

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