PHP学习心得


流接口模式

<h3>流接口模式目的</h3> <ul> <li>用来编写易于阅读的代码,就像自然语言一样(如英语)</li> </ul> <h2>代码示例</h2> <pre><code class="language-PHP">&lt;?php class Sql { /** * @var array */ private $fields = []; /** * @var array */ private $from = []; /** * @var array */ private $where = []; public function select(array $fields): Sql { $this-&gt;fields = $fields; return $this; } public function from(string $table, string $alias): Sql { $this-&gt;from[] = $table.' AS '.$alias; return $this; } public function where(string $condition): Sql { $this-&gt;where[] = $condition; return $this; } public function __toString(): string { return sprintf( 'SELECT %s FROM %s WHERE %s', join(', ', $this-&gt;fields), join(', ', $this-&gt;from), join(' AND ', $this-&gt;where) ); } } $query = (new Sql()) -&gt;select(['foo', 'bar']) -&gt;from('foobar', 'f') -&gt;where('f.bar = ?'); $this-&gt;assertEquals('SELECT foo, bar FROM foobar AS f WHERE f.bar = ?', (string) $query); </code></pre>

页面列表

ITEM_HTML