Last active
October 24, 2015 22:33
-
-
Save mageekguy/29cdf2e52d1c507f25b3 to your computer and use it in GitHub Desktop.
Mysqli and generator are in a boat...
This file contains 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 db; | |
class client | |
{ | |
private | |
$user, | |
$password, | |
$host, | |
$port, | |
$mysqli | |
; | |
function __construct($user = '', $password = '', $host = 'localhost', $port = 3306) | |
{ | |
$this->user = $user; | |
$this->password = $password; | |
$this->host = $host; | |
$this->port = $port; | |
} | |
function execute($query) | |
{ | |
if (! $this->mysqli) | |
{ | |
$mysqli = new \Mysqli($this->host, $this->user, $this->password, '', $this->port); | |
if ($mysqli->connect_errno) | |
{ | |
throw new \runtimeException('Unable to connect'); | |
} | |
$this->mysqli = $mysqli; | |
} | |
$result = $this->mysqli->query($query); | |
if ($result === false) | |
{ | |
throw new \runtimeException('Unable to execute \'' . $query . '\''); | |
} | |
return new result($this->mysqli->affected_rows, $result === true ? null : function() use ($result) { | |
$result->data_seek(0); | |
$key = 0; | |
while ($record = $result->fetch_assoc()) | |
{ | |
yield $key++ => $record; | |
} | |
} | |
); | |
} | |
} | |
final class result implements \iteratorAggregate | |
{ | |
private | |
$rows, | |
$generator | |
; | |
function __construct($rows, callable $generator = null) | |
{ | |
$this->rows = $rows; | |
$this->generator = $generator ?: function() { yield; }; | |
} | |
function __get($property) | |
{ | |
if ($property == 'rows') | |
{ | |
return $this->rows; | |
} | |
throw new \logicException('Undefined property: ' . $property); | |
} | |
function __set($property, $value) | |
{ | |
throw new \logicException(get_class($this) . ' is immutable'); | |
} | |
function __unset($property) | |
{ | |
throw new \logicException(get_class($this) . ' is immutable'); | |
} | |
function __isset($property) | |
{ | |
return $property == 'rows'; | |
} | |
function getIterator() | |
{ | |
return call_user_func($this->generator); | |
} | |
} | |
$result = (new client('root', 'qwjkuio3'))->execute('SELECT 1'); | |
var_dump($result->rows); | |
foreach ($result as $record1) | |
{ | |
$record1 = '1. ' . $record1[1]; | |
foreach ($result as $record2) | |
{ | |
var_dump($record1 . PHP_EOL . '2. ' . $record2[1]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment