PHP设计模式 - 流接口模式

2019-04-22 19:38 By 茹茹 2637 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学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

View in WeChat

Others Discussion

  • 分布式服务限流
    Posted on 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00
  • 为什么要测量尾部延迟
    Posted on 2020-09-18 10:34

1.621881s