Skip to content

Commit 5e0f328

Browse files
committed
improve the ORM
1 parent 6a59023 commit 5e0f328

File tree

4 files changed

+161
-64
lines changed

4 files changed

+161
-64
lines changed

app/Http/Controllers/HomeController.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ public function error404()
1313
}
1414
public function welcome()
1515
{
16+
$user = User::where([
17+
'username' => "Tores",
18+
])->firstOr(function () {
19+
return User::find(1);
20+
});
21+
var_dump($user) or die;
1622
return $this->view('welcome');
1723
}
1824
}

app/Models/Model.php

Lines changed: 149 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -2,40 +2,63 @@
22

33
namespace App\Models;
44

5+
use Closure;
56
use Database\DBConnection;
7+
use Exception;
68
use PDO;
79

810
class Model
911
{
1012

1113
protected static $db;
12-
static protected $table;
14+
protected static $table;
15+
protected static $primaryKey = "id";
1316
protected static $sql;
17+
protected static $params = [];
1418

1519
public function __construct()
1620
{
17-
self::$db = new DBConnection(DB, DB_NAME, DB_HOST, DB_USER, DB_PWD);
21+
static::$db = new DBConnection(DB, DB_NAME, DB_HOST, DB_USER, DB_PWD);
22+
}
23+
24+
public static function getInstance()
25+
{
26+
return new static();
1827
}
1928

2029
// select all data tables
21-
public static function all(): array
30+
public static function all(array $columns = ["*"]): array
2231
{
23-
self::$sql = "SELECT * FROM " . static::$table;
24-
return self::query();
32+
$columns = implode(',', $columns);
33+
static::$sql = "SELECT $columns FROM " . static::$table;
34+
return static::query();
2535
}
2636

27-
public static function lastId()
37+
public static function lastInsert()
2838
{
29-
return static::$db->getPDO()->lastInsertId();
39+
$id = static::$db->getPDO()->lastInsertId();
40+
return static::findOrFail($id);
3041
}
3142

3243
// select a row of table using id field
33-
public static function find(int $id)
44+
public static function find($id, array $columns = ['*'])
3445
{
35-
self::$sql = "SELECT * FROM " . static::$table . " WHERE id = ?";
36-
return self::query([$id], true);
46+
$columns = implode(",", $columns);
47+
static::$sql = "SELECT $columns FROM " . static::$table . " WHERE " . static::$primaryKey . " = ?";
48+
static::$params = [$id];
49+
return static::query(true);
3750
}
3851

52+
public static function findOrFail(int $id, array $columns = ['*'])
53+
{
54+
$result = static::find($id, $columns);
55+
if (is_null($result)) {
56+
throw new Exception("Model " . static::class . " not fount");
57+
}
58+
return $result;
59+
}
60+
61+
3962
// insert an instance in database
4063
public static function create(array $data)
4164
{
@@ -48,43 +71,83 @@ public static function create(array $data)
4871
$values .= ":{$key}{$comma}"; // set their value
4972
$i++;
5073
}
51-
self::$sql = "INSERT INTO " . static::$table . " ($fields) VALUES ($values)";
74+
static::$sql = "INSERT INTO " . static::$table . " ($fields) VALUES ($values)";
75+
static::$params = $data;
76+
static::query(true);
77+
return static::lastInsert();
78+
}
79+
80+
public function first(array $columns = ['*'])
81+
{
82+
return static::query(true);
83+
}
84+
85+
public function firstOrFail(array $columns = ['*'])
86+
{
87+
$result = $this->first($columns);
88+
if (empty($result)) {
89+
throw new Exception("Model " . static::class . " not fount");
90+
}
91+
return $result;
92+
}
5293

53-
return self::query($data);
94+
public function get(array $columns = ['*']): array
95+
{
96+
return static::query();
5497
}
5598

5699
public function oderBy(string $column, string $dir = "asc")
57100
{
58-
self::$sql .= " ORDER BY $column $dir";
59-
return self::query();
101+
static::$sql .= " ORDER BY $column $dir";
102+
return static::query();
60103
}
61104

62-
public static function __callStatic(string $name, array $parameters)
105+
public static function firstOrCreate(array $attributes = [], array $values = [])
63106
{
64-
$name = "static_" . $name;
65-
return call_user_func_array($name, $parameters);
107+
$result = static::where($attributes)->first();
108+
if (is_null($result)) {
109+
$result = static::create(array_merge($attributes, $values));
110+
}
111+
return $result;
66112
}
67113

68-
public function update($data)
114+
public static function updateOrCreate(array $attributes = [], array $values = [])
69115
{
70-
$sqlRequestPart = "";
116+
$result = static::where($attributes)->first();
117+
if ($result) {
118+
$result = $result->update($values);
119+
} else {
120+
$result = static::create(array_merge($attributes, $values));
121+
}
122+
return $result;
123+
}
71124

72-
$i = 1;
73-
foreach ($data as $key => $value) {
74-
$comma = $i === count($data) ? "" : ", ";
75-
$sqlRequestPart .= "{$key} = :{$key}{$comma}";
76-
$i++;
125+
public function firstOr($columns = ['*'], Closure $callback = null)
126+
{
127+
$result = $this->first();
128+
if ($result) {
129+
return $result;
77130
}
78-
$data['id'] = $this->id;
131+
if (is_callable($columns)) {
132+
return call_user_func_array($columns, []);
133+
}
134+
return call_user_func_array($callback, []);
135+
}
79136

80-
self::$sql = "UPDATE " . static::$table . " SET {$sqlRequestPart} WHERE id = :id";
81-
return self::query($data, true);
137+
public static function destroy($ids): bool
138+
{
139+
if (is_array($ids)) {
140+
$ids = implode(",", $ids);
141+
static::$sql = "DELETE FROM " . static::$table . " WHERE " . static::$primaryKey . " IN ($ids)";
142+
return static::query();
143+
}
144+
static::$sql = "DELETE FROM " . static::$table . " WHERE " . static::$primaryKey . " = ?";
145+
static::$params = [$ids];
146+
return static::query();
82147
}
83148

84-
// update row in database
85-
public static function static_update(int $id, array $data)
149+
public function update(array $data): bool
86150
{
87-
// create a part of sql for fields that we want to update
88151
$sqlRequestPart = "";
89152

90153
$i = 1;
@@ -93,65 +156,93 @@ public static function static_update(int $id, array $data)
93156
$sqlRequestPart .= "{$key} = :{$key}{$comma}";
94157
$i++;
95158
}
96-
$data['id'] = $id;
159+
$id = static::$primaryKey;
160+
$data[$id] = $this->$id;
97161

98-
self::$sql = "UPDATE " . static::$table . " SET {$sqlRequestPart} WHERE id = :id";
99-
return self::query($data, true);
162+
static::$sql = "UPDATE " . static::$table . " SET {$sqlRequestPart} WHERE " . static::$primaryKey . " = :" . static::$primaryKey;
163+
static::$params = $data;
164+
return static::query(true);
100165
}
101166

102-
public function delete()
167+
public function delete(): bool
103168
{
104-
self::$sql = "DELETE FROM " . static::$table . " WHERE id = ?";
105-
return self::query([$this->id]);
169+
static::$sql = "DELETE FROM " . static::$table . " WHERE " . static::$primaryKey . " = ?";
170+
$id = static::$primaryKey;
171+
static::$params = [$this->$id];
172+
static::query();
173+
return true;
106174
}
107-
// delete a row in database using id
108-
public static function static_delete(int $id): bool
175+
176+
177+
public static function where($column, $operator = null, $value = null)
109178
{
110-
self::$sql = "DELETE FROM " . static::$table . " WHERE id = ?";
111-
return self::query([$id]);
179+
$wheres = "";
180+
181+
if (is_array($column)) {
182+
$i = 1;
183+
foreach ($column as $key => $value) {
184+
$comma = $i === count($column) ? "" : " AND ";
185+
$wheres .= "{$key} = :{$key}{$comma}";
186+
$i++;
187+
}
188+
} else {
189+
$wheres = "$column $operator ?";
190+
}
191+
192+
$model = static::getInstance();
193+
194+
$model::$sql = "SELECT * FROM " . static::$table . " WHERE {$wheres}";
195+
$model::$params = is_array($column) ? $column : [$value];
196+
// var_dump($model::$sql);
197+
return $model;
112198
}
113199

114-
public static function where(array $params)
200+
public function orWhere($column, $operator = null, $value = null)
115201
{
116202
$wheres = "";
117203

118-
$i = 1;
119-
foreach ($params as $key => $value) {
120-
$comma = $i === count($params) ? "" : " AND ";
121-
$wheres .= "{$key} = :{$key}{$comma}";
122-
$i++;
204+
if (is_array($column)) {
205+
$i = 1;
206+
foreach ($column as $key => $value) {
207+
$comma = $i === count($column) ? "" : " OR ";
208+
$wheres .= "{$key} = :{$key}{$comma}";
209+
$i++;
210+
}
211+
} else {
212+
$wheres .= " OR $column $operator $value";
123213
}
124214

125-
self::$sql = "SELECT * FROM " . static::$table . " WHERE {$wheres}";
126-
return self::query($params);
215+
static::$sql .= "{$wheres}";
216+
return $this;
127217
}
128218

129219
/**
130220
* Set query for do something in database
131221
*
132-
* @param array|null $params If we want to make prepared request
133222
* @param bool $single For retrieve one instance
134223
*/
135-
private static function query(?array $params = null, bool $single = null)
224+
private static function query(bool $single = null)
136225
{
226+
$params = static::$params;
227+
static::$db = static::$db ?? new DBConnection(DB, DB_NAME, DB_HOST, DB_USER, DB_PWD);
137228
$method = is_null($params) ? 'query' : 'prepare';
138229
$fetch = is_null($single) ? 'fetchAll' : 'fetch';
139-
self::$db = new DBConnection(DB, DB_NAME, DB_HOST, DB_USER, DB_PWD);
140230

141-
if (strpos(self::$sql, 'INSERT') === 0 || strpos(self::$sql, 'UPDATE') === 0 || strpos(self::$sql, 'DELETE') === 0) {
142-
$stmt = self::$db->getPDO()->$method(self::$sql);
143-
$stmt->setFetchMode(PDO::FETCH_CLASS, self::class, [self::$db]);
231+
if (strpos(static::$sql, 'INSERT') === 0 || strpos(static::$sql, 'UPDATE') === 0 || strpos(static::$sql, 'DELETE') === 0) {
232+
$stmt = static::$db->getPDO()->$method(static::$sql);
233+
$stmt->setFetchMode(PDO::FETCH_CLASS, static::class, [static::$db]);
144234
return $stmt->execute($params);
145235
}
146236

147-
$stmt = self::$db->getPDO()->$method(self::$sql);
148-
$stmt->setFetchMode(PDO::FETCH_CLASS, self::class, [self::$db]);
237+
$stmt = static::$db->getPDO()->$method(static::$sql);
238+
$stmt->setFetchMode(PDO::FETCH_CLASS, static::class, [static::$db]);
149239

150240
if ($method === 'query') {
151-
return $stmt->$fetch();
241+
$results = $stmt->$fetch();
152242
} else {
153243
$stmt->execute($params);
154-
return $stmt->$fetch();
244+
$results = $stmt->$fetch();
155245
}
246+
return $results;
156247
}
157248
}

public/index.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@
1818

1919
$router = new Router();
2020

21-
$router->get('/404', 'App\Controllers\HomeController@error404');
22-
$router->get('/', 'App\Controllers\HomeController@welcome');
21+
$router->get('/404', 'App\Http\Controllers\HomeController@error404');
22+
$router->get('/', 'App\Http\Controllers\HomeController@welcome');
2323
$router->get('/welcome', [HomeController::class, 'welcome']);
24-
$router->get('/user/:user', function (Request $request, $user) {
25-
echo "My name is $user->username and I'm 22 years old";
26-
// var_dump($request);
24+
$router->get('/user/:user', function (Request $request, User $user) {
25+
// echo "My name is $user->email and I'm 22 years old";
26+
var_dump($user);
2727
}, "test");
2828
// echo $router->generate("test", ['fernand', 15]);
2929
$router->run();

routes/Route.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public function execute()
5757
$model = ucfirst($key);
5858
$parameters = [];
5959
$model = "App\\Models\\$model";
60-
$parameters[] = $model::find($value);
60+
$parameters[] = $model::findOrFail($value);
6161
}
6262
// var_dump($parameters) or die;
6363
$params = array_merge($params, $parameters);

0 commit comments

Comments
 (0)