start a restructure

This commit is contained in:
Antonio Spinelli
2014-03-21 18:03:44 -03:00
parent b0b0d4a1a4
commit e59d70a0ac
180 changed files with 21 additions and 16 deletions

View File

@@ -0,0 +1,11 @@
# Fluent Interface
## Purpose
To write code that is easy readable just like sentences in a natural language (like English).
## Examples
* Doctrine2's QueryBuilder works something like that example class below
* PHPUnit uses fluent interfaces to build mock objects
* Yii Framework: CDbCommand and CActiveRecord use this pattern, too

View File

@@ -0,0 +1,80 @@
<?php
namespace DesignPatterns\FluentInterface;
/**
* class SQL
*/
class SQL
{
/**
* @var array
*/
protected $fields = array();
/**
* @var array
*/
protected $from = array();
/**
* @var array
*/
protected $where = array();
/**
* adds select fields
*
* @param array $fields
*
* @return SQL
*/
public function select(array $fields = array())
{
$this->fields = $fields;
return $this;
}
/**
* adds a FROM clause
*
* @param string $table
* @param string $alias
*
* @return SQL
*/
public function from($table, $alias)
{
$this->from[] = $table . ' AS ' . $alias;
return $this;
}
/**
* adds a WHERE condition
*
* @param string $condition
*
* @return SQL
*/
public function where($condition)
{
$this->where[] = $condition;
return $this;
}
/**
* Gets the query, just an example of building a query,
* no check on consistency
*
* @return string
*/
public function getQuery()
{
return 'SELECT ' . implode(',', $this->fields)
. ' FROM ' . implode(',', $this->from)
. ' WHERE ' . implode(' AND ', $this->where);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace DesignPatterns\Tests\FluentInterface;
use DesignPatterns\FluentInterface\SQL;
/**
* FluentInterfaceTest tests the fluent interface SQL
*/
class FluentInterfaceTest extends \PHPUnit_Framework_TestCase
{
public function testBuildSQL()
{
$instance = new SQL();
$query = $instance->select(array('foo', 'bar'))
->from('foobar', 'f')
->where('f.bar = ?')
->getQuery();
$this->assertEquals('SELECT foo,bar FROM foobar AS f WHERE f.bar = ?', $query);
}
}