Skip to content

Instantly share code, notes, and snippets.

@TakahashiIkki
Created December 19, 2019 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TakahashiIkki/f1217acf341c9033e4e8da78373d7df9 to your computer and use it in GitHub Desktop.
Save TakahashiIkki/f1217acf341c9033e4e8da78373d7df9 to your computer and use it in GitHub Desktop.
<?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