Skip to content

Instantly share code, notes, and snippets.

@f3ath
Last active April 6, 2018 01:34
Show Gist options
  • Save f3ath/13719ef77c649dc9386b9fa779c043ad to your computer and use it in GitHub Desktop.
Save f3ath/13719ef77c649dc9386b9fa779c043ad to your computer and use it in GitHub Desktop.
<?php
class PdoArgs implements IteratorAggregate
{
/**
* @var array
*/
private $state;
public static function factory(string $username = null, string $password = null)
{
return new self([
'dsn' => "sqlite::memory:",
'username' => $username,
'password' => $password,
'options' => []
]);
}
private function __construct(array $state)
{
$this->state = $state;
}
public function withErrorModeException(): self
{
return $this->withOptions([PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
}
public function getIterator(): Traversable
{
return new ArrayIterator([
$this->state['dsn'],
$this->state['username'],
$this->state['password'],
$this->state['options'],
]);
}
public function withOptions(array $options): self
{
$state = $this->state;
$state['options'] = array_replace($state['options'], $options);
return new self($state);
}
}
$pdo = new PDO(...PdoArgs::factory()->withErrorModeException());
$select = $pdo->prepare('SELECT 1 + 1');
$select->execute();
var_dump($select->fetchAll());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment