流模式

在软件工程中,流接口(Fluent Interface)是指实现一种面向对象的、能提高代码可读性的 API 的方法,其目的就是可以编写具有自然语言一样可读性的代码,我们对这种代码编写方式还有一个通俗的称呼 —— 方法链。
 1 <?php
 2 
 3 class Sql
 4 {
 5     /**
 6      * @var array
 7      */
 8     protected $fields = array();
 9 
10     /**
11      * @var array
12      */
13     protected $from = array();
14 
15     /**
16      * @var array
17      */
18     protected $where = array();
19 
20     /**
21      * 添加 select 字段
22      *
23      * @param array $fields
24      *
25      * @return SQL
26      */
27     public function select(array $fields = array())
28     {
29         $this->fields = $fields;
30 
31         return $this;
32     }
33 
34     /**
35      * 添加 FROM 子句
36      *
37      * @param string $table
38      * @param string $alias
39      *
40      * @return SQL
41      */
42     public function from($table, $alias)
43     {
44         $this->from[] = $table . ' AS ' . $alias;
45 
46         return $this;
47     }
48 
49     /**
50      * 添加 WHERE 条件
51      *
52      * @param string $condition
53      *
54      * @return SQL
55      */
56     public function where($condition)
57     {
58         $this->where[] = $condition;
59 
60         return $this;
61     }
62 
63     /**
64      * 生成查询语句
65      *
66      * @return string
67      */
68     public function getQuery()
69     {
70         return 'SELECT ' . implode(',', $this->fields)
71         . ' FROM ' . implode(',', $this->from)
72         . ' WHERE ' . implode(' AND ', $this->where);
73     }
74 }
75 
76 
77 
78 
79 $instance = new Sql();
80 $query = $instance->select(array('foo', 'bar'))
81                     ->from('foobar', 'f')
82                     ->where('f.bar = ?')
83                     ->getQuery();
View Code
原文地址:https://www.cnblogs.com/hangtt/p/6263989.html