Created
December 19, 2019 14:24
-
-
Save TakahashiIkki/f1217acf341c9033e4e8da78373d7df9 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Class SQLBuilder | |
*/ | |
class SQLBuilder | |
{ | |
private $from_table = null; | |
/** @var array */ | |
private $select_columns = []; | |
public function clear() | |
{ | |
$this->from_table = null; | |
$this->select_columns = []; | |
return $this; | |
} | |
public function from($table_name) | |
{ | |
$this->from_table = $table_name; | |
return $this; | |
} | |
public function select($columns = '*') | |
{ | |
if (is_string($columns)) { | |
$columns = explode(',', $columns); | |
} | |
foreach ($columns as $column) { | |
$column = trim($column); | |
if ($column) { | |
$this->select_columns[] = $column; | |
} | |
} | |
return $this; | |
} | |
public function text() | |
{ | |
/* SQLインジェクション... */ | |
return 'SELECT ' . $this->parse_select_columns() . ' FROM ' . $this->from_table; | |
} | |
private function parse_select_columns() | |
{ | |
$select_columns = $this->select_columns; | |
if (empty($select_columns)) { | |
$select_columns = ['*']; | |
} | |
/* SQLインジェクション... */ | |
return implode(',', $select_columns); | |
} | |
} | |
class MySQL_Connector | |
{ | |
/** | |
* @param SQLBuilder $builder | |
*/ | |
public function execute($builder) | |
{ | |
echo $builder->text(); | |
} | |
} | |
class User | |
{ | |
/** @var MySQL_Connector */ | |
private $connector; | |
/** @var SQLBuilder $builder */ | |
private $builder; | |
public function __construct() | |
{ | |
$this->connector = new MySQL_Connector(); | |
$this->builder = new SQLBuilder(); | |
} | |
public function get_user_name() | |
{ | |
$this->builder = $this->builder->clear()->select(['user_name'])->from('users'); | |
$this->connector->execute($this->builder); | |
} | |
public function get_user() | |
{ | |
$this->builder = $this->builder->clear()->from('users'); | |
$this->connector->execute($this->builder); | |
} | |
} | |
echo " ------- \n"; | |
$user = new User(); | |
$user->get_user(); | |
echo "\n ------- \n"; | |
$user->get_user_name(); | |
echo "\n ------- \n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment