finished!
[mdref/mdref-pq] / pq / Converter.md
1 # interface pq\Converter
2
3 Interface for type conversions.
4
5 ## Example:
6
7 <?php
8
9 /**
10 * Naive geometric point
11 */
12 class Point {
13 public $x;
14 public $y;
15 function __construct($x, $y) {
16 $this->x = $x;
17 $this->y = $y;
18 }
19 }
20
21 /**
22 * A simple Box
23 */
24 class Box {
25 public $p1;
26 public $p2;
27 function __construct(Point $p1, Point $p2) {
28 $this->p1 = $p1;
29 $this->p2 = $p2;
30 }
31 }
32
33 /**
34 * Our converter handles only objects of type box
35 */
36 class BoxConverter implements pq\Converter {
37 private $oid;
38 function __construct(pq\Types $types) {
39 $this->oid = $types["box"]->oid;
40 }
41
42 /**
43 * @return array
44 * @see pq\Converter::convertTypes()
45 */
46 function convertTypes() {
47 return [$this->oid];
48 }
49
50 /**
51 * @return string
52 * @param $box Box
53 * @see pq\Converter::convertToString()
54 */
55 function convertToString($box, $type = NULL) {
56 return sprintf("(%F,%F),(%F,%F)",
57 $box->p1->x, $box->p1->y,
58 $box->p2->x, $box->p2->y
59 );
60 }
61
62 /**
63 * @return Box
64 * @param string $data
65 * @see pq\Converter::convertFromString()
66 */
67 function convertFromString($data, $type = NULL) {
68 list($p1x, $p1y, $p2x, $p2y) = sscanf($data, "(%f,%f),(%f,%f)");
69 return new Box(new Point($p1x, $p1y), new Point($p2x, $p2y));
70 }
71 }
72
73 $conn = new pq\Connection;
74 $types = new pq\Types($conn);
75 $conv = new BoxConverter($types);
76 $inbox = new Box(new Point(1.1, 2.2), new Point(3.3, 4.4));
77
78 $conn->setConverter($conv);
79 $result = $conn->execParams("SELECT \$1", [$inbox], [$types["box"]->oid]);
80 $result->fetchCol($outbox);
81
82 var_dump($outbox);
83
84 ?>
85
86 Yields:
87
88 object(Box)#163 (2) {
89 ["p1"]=>
90 object(Point)#164 (2) {
91 ["x"]=>
92 float(3.3)
93 ["y"]=>
94 float(4.4)
95 }
96 ["p2"]=>
97 object(Point)#165 (2) {
98 ["x"]=>
99 float(1.1)
100 ["y"]=>
101 float(2.2)
102 }
103 }