php接口模式,PHP设计模式 - 流接口模式

【一】模式定义

在软件工程中,流接口是指实现一种面向对象的、能提高代码可读性的 API 的方法,其目的就是可以编写具有自然语言一样可读性的代码,我们对这种代码编写方式还有一个通俗的称呼 —— 方法链。

【二】UML 类图

0c2368c268e7ac4e3b14784a9919e67e.png

【三】示例代码

Sql.php

namespace DesignPatterns\Structural\FluentInterface;

/**

* SQL 类

*/

class Sql

{

/**

* @var array

*/

protected $fields = array();

/**

* @var array

*/

protected $from = array();

/**

* @var array

*/

protected $where = array();

/**

* 添加 select 字段

*

* @param array $fields

*

* @return SQL

*/

public function select(array $fields = array())

{

$this->fields = $fields;

return $this;

}

/**

* 添加 FROM 子句

*

* @param string $table

* @param string $alias

*

* @return SQL

*/

public function from($table, $alias)

{

$this->from[] = $table . ' AS ' . $alias;

return $this;

}

/**

* 添加 WHERE 条件

*

* @param string $condition

*

* @return SQL

*/

public function where($condition)

{

$this->where[] = $condition;

return $this;

}

/**

* 生成查询语句

*

* @return string

*/

public function getQuery()

{

return 'SELECT ' . implode(',', $this->fields)

. ' FROM ' . implode(',', $this->from)

. ' WHERE ' . implode(' AND ', $this->where);

}

}

【四】测试代码

Tests/FluentInterfaceTest.php

namespace DesignPatterns\Structural\FluentInterface\Tests;

use DesignPatterns\Structural\FluentInterface\Sql;

/**

* FluentInterfaceTest 测试流接口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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值