流接口模式

<?php
declare(strict_types=1);

// php 技術羣:781742505
// 鏈式編程
// 典型例子:Query Builder,PHPUnit

/**
 * Class Sql
 */
class Sql
{
    /**
     * @var array
     */
    private $fields = [];

    /**
     * @var array
     */
    private $from = [];

    /**
     * @var array
     */
    private $where = [];

    /**
     * @param array $fields
     *
     * @return Sql
     */
    public function select(array $fields): Sql
    {
        $this->fields = $fields;

        return $this;
    }

    /**
     * @param string $table
     * @param string $alias
     *
     * @return Sql
     */
    public function from(string $table, string $alias): Sql
    {
        $this->from[] = $table.' AS '.$alias;

        return $this;
    }

    /**
     * @param string $condition
     *
     * @return Sql
     */
    public function where(string $condition): Sql
    {
        $this->where[] = $condition;

        return $this;
    }

    /**
     * @return string
     */
    public function __toString(): string
    {
        return sprintf(
            'SELECT %s FROM %s WHERE %s',
            join(', ', $this->fields),
            join(', ', $this->from),
            join(' AND ', $this->where)
        );
    }
}

(new Sql())->select(['foo', 'bar'])->from('foobar', 'f')
    ->where('f.bar = ?');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章