typo
[mdref/mdref-pq] / pq / Connection / setConverter.md
1 # void pq\Connection::setConverter(pq\Converter $converter)
2
3 Set a data type converter.
4
5 ## Params:
6
7 * pq\Converter $converter
8 An instance implementing pq\Converter.
9
10 ## Throws:
11
12 * pq\Exception\InvalidArgumentException
13 * pq\Exception\BadMethodCallException
14
15 ## Example:
16
17 <?php
18
19 class HStoreConverter implements pq\Converter
20 {
21 private $oids;
22
23 function __construct(pq\Types $types) {
24 $this->oids = [$types["hstore"]->oid];
25 }
26
27 function convertTypes() {
28 return $this->oids;
29 }
30
31 function convertFromString($string) {
32 return eval("return [$string];");
33 }
34
35 function convertToString($data) {
36 $string = "";
37 foreach ($data as $k => $v) {
38 if (isset($v)) {
39 $string .= sprintf("\"%s\"=>\"%s\",", addslashes($k), addslashes($v));
40 } else {
41 $string .= sprintf("\"%s\"=>NULL,", addslashes($k));
42 }
43 }
44 return $string;
45 }
46 }
47 $connection = new pq\Connection;
48 $types = new pq\Types($connection);
49
50 $connection->setConverter(new HStoreConverter($types));
51
52 $result = $connection->execParams("SELECT \$1", [
53 [
54 "k1" => "v1",
55 "k2" => "v2",
56 "k3" => null
57 ]
58 ], [
59 $types["hstore"]->oid
60 ]);
61
62 var_dump(current($result->fetchAll()));
63
64 ?>
65
66 Yields:
67
68 array(1) {
69 [0]=>
70 array(3) {
71 ["k1"]=>
72 string(2) "v1"
73 ["k2"]=>
74 string(2) "v2"
75 ["k3"]=>
76 NULL
77 }
78 }