Last active
December 28, 2015 05:09
-
-
Save chanmix51/7447181 to your computer and use it in GitHub Desktop.
Using composite types with PgRow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TYPE postal_address AS ( | |
place text, | |
postal_code char(5), | |
city varchar, | |
cedex char | |
); | |
CREATE TABLE customer ( | |
name varchar NOT NULL, | |
address postal_address NOT NULL CHECK ( | |
(address).place IS NOT NULL | |
AND | |
(address).postal_code IS NOT NULL | |
AND | |
(address).city IS NOT NULL | |
) | |
) | |
; | |
INSERT INTO customer (name, address) VALUES ( | |
'john doe', | |
('27, route des plages', '56590', 'groix', null) | |
) | |
; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Database\Type; | |
use \Pomm\Type\Composite; | |
class Address extends Composite | |
{ | |
public $place; | |
public $postal_code; | |
public $city; | |
public $cedex; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// .. | |
$database->registerConverter( | |
'PostalAddress', | |
new \Pomm\Converter\PgRow( | |
$database, | |
new \Pomm\Object\RowStructure( | |
array( | |
'place' => 'text', | |
'postal_code' => 'char', | |
'city' => 'varchar', | |
'cedex' => 'char' | |
)), | |
'\My\Database\Type\AddressType' // <- if not provided, arrays will be returned instead | |
), | |
array('public.postal_address', 'postal_address') | |
) | |
); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$customers = $connection | |
->getMapFor('\MyProject\MySchema\Customer') | |
->findWhere('name ~ $*', array('^john')); | |
foreach ($customers as $customer) | |
{ | |
printf("%s lives in %s (%s).\n", | |
$customer->name, | |
$customer->address->city, | |
$customer->address->postal_code | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment