Skip to content

Instantly share code, notes, and snippets.

@kamiazya
Created March 7, 2020 05:16
Show Gist options
  • Save kamiazya/9923ed7d3094216bc60766d79a092954 to your computer and use it in GitHub Desktop.
Save kamiazya/9923ed7d3094216bc60766d79a092954 to your computer and use it in GitHub Desktop.
<?php
interface DB {
public function findOne($query, $params);
public function findAll($query, $params);
}
interface Repositry {
public function getById(int $id);
}
class UsersRepositry implements Repositry {
private $db;
function __construct(DB $db) {
$this->db = $db;
}
public function getById(int $id) {
return $this->db->findOne(
[
'from' => 'users',
'where' => [
'id = ?'
]
],
[ $id ]);
}
}
class MySQL implements DB {
public $client;
function __construct() {
// MySQLへの接続など
}
private function toSQL($query) {
return /** TODO */;
}
public function findOne($query, $params) {
$sql = $this->toSQL($query);
return $this->client->query($sql)->exec($params)->next();
}
public function findAll($query, $params) {
$sql = $this->toSQL($query);
return $this->client->query($sql)->exec($params)->all();
}
}
class MongoDB implements DB {
public $client;
function __construct() {
// MongoDBへの接続など
}
private function toMongoQuery($query, $params) {
return /** TODO */;
}
public function findOne($query, $params) {
$mongoQuery = $this->toMongoQuery($query);
return $this->client->find_one($mongoQuery, $params);
}
public function findAll($query, $params) {
$mongoQuery = $this->toMongoQuery($query);
return $this->client->find($mongoQuery, $params);
}
}
$mysql = new MySQL(/** TODO */);
// $mongo = new MongoDB(/** TODO */);
$users = new UsersRepositry($mysql);
// $users = new UsersRepositry($mongo);
// $users->getById(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment