PHP设计模式 - 流接口模式

2019-04-22 19:38 By 茹茹 2755 0 0

【一】模式定义

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


【二】UML 类图

image.png


【三】示例代码

Sql.php

<?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

<?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);
    }
}


注:本文转载自 Laravel学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

Others Discussion

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • ACID原则
    Posted on 2020-12-17 16:36
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • MySQL分组
    Posted on 2019-11-18 14:00