目的
用來編寫易於閱讀的代碼,就像自然語言一樣(如英語)
例子
Yii 框架:CDbCommand 與 CActiveRecord 也使用此模式
Doctrine2 的 QueryBuilder,就像下面例子中類似
PHPUnit 使用連貫接口來創建 mock 對象
UML圖
代碼
- Sql.php
<?php
namespace DesignPatterns\Structural\FluentInterface;
class Sql
{
/**
* @var array
*/
private $fields = [];
/**
* @var array
*/
private $from = [];
/**
* @var array
*/
private $where = [];
public function select(array $fields): Sql
{
$this->fields = $fields;
return $this;
}
public function from(string $table, string $alias): Sql
{
$this->from[] = $table.' AS '.$alias;
return $this;
}
public function where(string $condition): Sql
{
$this->where[] = $condition;
return $this;
}
public function __toString(): string
{
return sprintf(
'SELECT %s FROM %s WHERE %s',
join(', ', $this->fields),
join(', ', $this->from),
join(' AND ', $this->where)
);
}
}
測試
- Tests/FluentInterfaceTest.php
<?php
namespace DesignPatterns\Structural\FluentInterface\Tests;
use DesignPatterns\Structural\FluentInterface\Sql;
use PHPUnit\Framework\TestCase;
class FluentInterfaceTest extends TestCase
{
public function testBuildSQL()
{
$query = (new Sql())
->select(['foo', 'bar'])
->from('foobar', 'f')
->where('f.bar = ?');
$this->assertEquals('SELECT foo, bar FROM foobar AS f WHERE f.bar = ?', (string) $query);
}
}
PHP 互聯網架構師 50K 成長指南+行業問題解決總綱(持續更新)
面試10家公司,收穫9個offer,2020年PHP 面試問題
★如果喜歡我的文章,想與更多資深開發者一起交流學習的話,獲取更多大廠面試相關技術諮詢和指導,歡迎加入我們的羣啊,暗號:phpzh(君羊號碼856460874)。
內容不錯的話希望大家支持鼓勵下點個贊/喜歡,歡迎一起來交流;另外如果有什麼問題 建議 想看的內容可以在評論提出