Skip to content

Commit b6ea192

Browse files
jkapuscik2jkapuscik2
authored andcommitted
Added fluent interface
1 parent cdb6188 commit b6ea192

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
namespace Structural\FluentInterface;
4+
5+
class QueryBuilder
6+
{
7+
8+
private string $query = "";
9+
10+
public function select(array $fields = []): QueryBuilder
11+
{
12+
$this->query .= sprintf("SELECT %s ", sizeof($fields) ? implode(", ", $fields) : "*");
13+
14+
return $this;
15+
}
16+
17+
public function from(string $tableName): QueryBuilder
18+
{
19+
$this->query .= " FROM {$tableName} ";
20+
21+
return $this;
22+
}
23+
24+
public function where(array $conditions): QueryBuilder
25+
{
26+
$this->query .= sprintf("WHERE %s ", implode(" AND ", $conditions));
27+
28+
return $this;
29+
}
30+
31+
public function offset(int $offset): QueryBuilder
32+
{
33+
$this->query .= "OFFSET {$offset} ";
34+
35+
return $this;
36+
}
37+
38+
public function limit(int $limit): QueryBuilder
39+
{
40+
$this->query .= "LIMIT {$limit} ";
41+
42+
return $this;
43+
}
44+
45+
public function orderBy(string $orderRule): QueryBuilder
46+
{
47+
$this->query .= "ORDER BY {$orderRule} ";
48+
49+
return $this;
50+
}
51+
52+
public function getQuery() : string
53+
{
54+
return $this->query;
55+
}
56+
}

structural/FluentInterface/demo.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
namespace Structural\FluentInterface;
4+
5+
require(__DIR__ . '/../../vendor/autoload.php');
6+
7+
echo (new QueryBuilder())
8+
->select(["name", "surname"])
9+
->from("users")
10+
->where(["name = 'John'", "city = 'Warsaw'"])
11+
->orderBy("date ASC")
12+
->limit(10)
13+
->getQuery();
14+

0 commit comments

Comments
 (0)