W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
用來編寫易于閱讀的代碼,就像自然語言一樣(如英語)
Sql.php
<?php declare(strict_types=1); namespace DesignPatterns\Structural\FluentInterface; class Sql implements \Stringable { private array $fields = []; private array $from = []; private array $where = []; public function select(array $fields): Sql { $this->fields = $fields; return $this; } public function from(string $table, string $alias): Sql { $this->from[] = $table . ' AS ' . $alias; return $this; } public function where(string $condition): Sql { $this->where[] = $condition; return $this; } public function __toString(): string { return sprintf( 'SELECT %s FROM %s WHERE %s', join(', ', $this->fields), join(', ', $this->from), join(' AND ', $this->where) ); } }
Tests/FluentInterfaceTest.php
<?php declare(strict_types=1); namespace DesignPatterns\Structural\FluentInterface\Tests; use DesignPatterns\Structural\FluentInterface\Sql; use PHPUnit\Framework\TestCase; class FluentInterfaceTest extends TestCase { public function testBuildSQL() { $query = (new Sql()) ->select(['foo', 'bar']) ->from('foobar', 'f') ->where('f.bar = ?'); $this->assertSame('SELECT foo, bar FROM foobar AS f WHERE f.bar = ?', (string) $query); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: