-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path03-scopes.php
More file actions
392 lines (332 loc) · 10.7 KB
/
03-scopes.php
File metadata and controls
392 lines (332 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
/**
* Example: Query Scopes.
*
* Demonstrates global and local scopes for query building.
*
* Usage:
* php examples/28-query-scopes/01-scopes-examples.php
* PDODB_DRIVER=mysql php examples/28-query-scopes/01-scopes-examples.php
* PDODB_DRIVER=pgsql php examples/28-query-scopes/01-scopes-examples.php
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\helpers\Db;
use tommyknocker\pdodb\orm\Model;
// Define models with scopes
class Post extends Model
{
public static function tableName(): string
{
return 'posts';
}
public static function primaryKey(): array
{
return ['id'];
}
/**
* Global scopes are automatically applied to all queries.
*/
public static function globalScopes(): array
{
return [
'notDeleted' => function ($query) {
$query->whereRaw('deleted_at IS NULL');
return $query;
},
];
}
/**
* Local scopes are applied only when explicitly called.
*/
public static function scopes(): array
{
return [
'published' => function ($query) {
$query->where('status', 'published');
return $query;
},
'draft' => function ($query) {
$query->where('status', 'draft');
return $query;
},
'popular' => function ($query) {
$query->where('view_count', 1000, '>');
return $query;
},
'recent' => function ($query, $days = 7) {
$date = date('Y-m-d H:i:s', strtotime("-$days days"));
$query->where('created_at', $date, '>=');
return $query;
},
'byAuthor' => function ($query, $authorId) {
$query->where('author_id', $authorId);
return $query;
},
];
}
}
class User extends Model
{
public static function tableName(): string
{
return 'users';
}
public static function primaryKey(): array
{
return ['id'];
}
/**
* Global scope: only active users.
*/
public static function globalScopes(): array
{
return [
'active' => function ($query) {
$query->where('is_active', 1);
return $query;
},
];
}
/**
* Local scopes for user queries.
*/
public static function scopes(): array
{
return [
'verified' => function ($query) {
$query->whereRaw('email_verified_at IS NOT NULL');
return $query;
},
'withRole' => function ($query, $role) {
$query->where('role', $role);
return $query;
},
];
}
}
$db = createExampleDb();
$driver = getCurrentDriver($db);
echo "=== Query Scopes Example (on $driver) ===\n\n";
// Create tables using fluent API (cross-dialect)
$schema = $db->schema();
$schema->dropTableIfExists('posts');
$schema->dropTableIfExists('users');
$schema->createTable('posts', [
'id' => $schema->primaryKey(),
'title' => $schema->string(255)->notNull(),
'status' => $schema->string(50)->defaultValue('draft'),
'author_id' => $schema->integer(),
'view_count' => $schema->integer()->defaultValue(0),
'deleted_at' => $schema->timestamp(),
'created_at' => $schema->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),
]);
$schema->createTable('users', [
'id' => $schema->primaryKey(),
'name' => $schema->string(255)->notNull(),
'email' => $schema->string(255)->notNull(),
'role' => $schema->string(50)->defaultValue('user'),
'is_active' => $schema->integer()->defaultValue(1),
'email_verified_at' => $schema->timestamp(),
]);
Post::setDb($db);
User::setDb($db);
echo "✓ Tables created\n\n";
// Example 1: Local Scopes
echo "1. Local Scopes (Applied On-Demand)\n";
echo "-------------------------------------\n";
// Insert test data
$postId1 = $db->find()->table('posts')->insert([
'title' => 'Published Post 1',
'status' => 'published',
'view_count' => 1500,
'author_id' => 1,
]);
$postId2 = $db->find()->table('posts')->insert([
'title' => 'Draft Post',
'status' => 'draft',
'view_count' => 100,
'author_id' => 1,
]);
$postId3 = $db->find()->table('posts')->insert([
'title' => 'Published Post 2',
'status' => 'published',
'view_count' => 500,
'author_id' => 2,
]);
// Use local scope
$publishedPosts = Post::find()->scope('published')->all();
echo "Published posts: " . count($publishedPosts) . "\n";
foreach ($publishedPosts as $post) {
echo " - {$post->title}\n";
}
// Chain multiple scopes
$popularPublished = Post::find()
->scope('published')
->scope('popular')
->all();
echo "\nPopular published posts: " . count($popularPublished) . "\n";
foreach ($popularPublished as $post) {
echo " - {$post->title} (views: {$post->view_count})\n";
}
echo "\n";
// Example 2: Scope with Parameters
echo "2. Scope with Parameters\n";
echo "-------------------------\n";
$now = time();
$recentDate = date('Y-m-d H:i:s', $now - 2 * 24 * 3600);
$oldDate = date('Y-m-d H:i:s', $now - 10 * 24 * 3600);
$db->find()->table('posts')->insert([
'title' => 'Recent Post',
'status' => 'published',
'created_at' => $driver === 'oci' ? Db::toTs($recentDate) : $recentDate,
]);
$db->find()->table('posts')->insert([
'title' => 'Old Post',
'status' => 'published',
'created_at' => $driver === 'oci' ? Db::toTs($oldDate) : $oldDate,
]);
// Use scope with parameter
$recentPosts = Post::find()
->scope('published')
->scope('recent', 5) // last 5 days
->all();
echo "Recent posts (last 5 days): " . count($recentPosts) . "\n";
foreach ($recentPosts as $post) {
echo " - {$post->title}\n";
}
echo "\n";
// Example 3: Global Scopes (Automatic)
echo "3. Global Scopes (Automatically Applied)\n";
echo "-----------------------------------------\n";
$deletedDate = date('Y-m-d H:i:s');
$db->find()->table('posts')->insert([
'title' => 'Deleted Post',
'status' => 'published',
'deleted_at' => $driver === 'oci' ? Db::toTs($deletedDate) : $deletedDate,
]);
// Global scope automatically filters out deleted posts
$allActivePosts = Post::find()->all();
echo "Active posts (excluding deleted): " . count($allActivePosts) . "\n";
foreach ($allActivePosts as $post) {
if (isset($post->deleted_at) && $post->deleted_at !== null) {
echo " ERROR: Deleted post found!\n";
} else {
echo " - {$post->title}\n";
}
}
echo "\n";
// Example 4: Disable Global Scope
echo "4. Disable Global Scope\n";
echo "------------------------\n";
// Temporarily disable global scope to get all posts including deleted
$allPostsIncludingDeleted = Post::find()
->withoutGlobalScope('notDeleted')
->all();
echo "All posts (including deleted): " . count($allPostsIncludingDeleted) . "\n";
foreach ($allPostsIncludingDeleted as $post) {
$deleted = isset($post->deleted_at) && $post->deleted_at !== null ? ' [DELETED]' : '';
echo " - {$post->title}{$deleted}\n";
}
echo "\n";
// Example 5: Combining Scopes
echo "5. Combining Global and Local Scopes\n";
echo "-------------------------------------\n";
// Insert users
$verifiedDate = date('Y-m-d H:i:s');
$userId1 = $db->find()->table('users')->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
'role' => 'admin',
'is_active' => 1,
'email_verified_at' => $driver === 'oci' ? Db::toTs($verifiedDate) : $verifiedDate,
]);
$userId2 = $db->find()->table('users')->insert([
'name' => 'Jane Smith',
'email' => 'jane@example.com',
'role' => 'user',
'is_active' => 1,
'email_verified_at' => null,
]);
$userId3 = $db->find()->table('users')->insert([
'name' => 'Inactive User',
'email' => 'inactive@example.com',
'role' => 'user',
'is_active' => 0,
]);
// Global scope filters active users, local scope filters verified
$activeVerifiedUsers = User::find()
->scope('verified')
->all();
echo "Active and verified users: " . count($activeVerifiedUsers) . "\n";
foreach ($activeVerifiedUsers as $user) {
echo " - {$user->name} ({$user->email})\n";
}
echo "\n";
// Example 6: Scope with QueryBuilder Directly
echo "6. Scope with QueryBuilder (Without Model)\n";
echo "-------------------------------------------\n";
// Use scope directly with QueryBuilder
$result = $db->find()
->from('posts')
->scope(function ($query) {
return $query->where('status', 'published')
->andWhere('view_count', 1000, '>');
})
->limit(5)
->get();
echo "Posts using direct QueryBuilder scope: " . count($result) . "\n";
foreach ($result as $row) {
echo " - {$row['title']} (views: {$row['view_count']})\n";
}
echo "\n";
// Example 7: Scopes at PdoDb Level
echo "7. Scopes at PdoDb Level (QueryBuilder)\n";
echo "-----------------------------------------------\n";
// Clear any existing scopes
$scopes = $db->getScopes();
foreach (array_keys($scopes) as $scopeName) {
$db->removeScope($scopeName);
}
// Drop and recreate a simple table for this example using fluent API
$schema->dropTableIfExists('items');
$schema->createTable('items', [
'id' => $schema->primaryKey(),
'name' => $schema->string(255)->notNull(),
'is_active' => $schema->integer()->defaultValue(1),
'tenant_id' => $schema->integer(),
]);
// Insert test data
$db->find()->table('items')->insert(['name' => 'Item 1', 'is_active' => 1, 'tenant_id' => 1]);
$db->find()->table('items')->insert(['name' => 'Item 2', 'is_active' => 0, 'tenant_id' => 1]);
$db->find()->table('items')->insert(['name' => 'Item 3', 'is_active' => 1, 'tenant_id' => 2]);
// Add scopes to PdoDb (applies to all queries)
$db->addScope('active', function ($query) {
return $query->where('is_active', 1);
});
$db->addScope('tenant', function ($query) {
$tenantId = 1; // Simulate current tenant
return $query->where('tenant_id', $tenantId);
});
// All queries automatically apply scopes
$items = $db->find()->from('items')->get();
echo "Items with scopes: " . count($items) . "\n";
foreach ($items as $item) {
echo " - {$item['name']}\n";
}
// Temporarily disable a scope
$allActiveItems = $db->find()
->from('items')
->withoutGlobalScope('tenant')
->get();
echo "\nAll active items (tenant scope disabled): " . count($allActiveItems) . "\n";
// Remove scope completely
$db->removeScope('tenant');
$itemsAfterRemoval = $db->find()->from('items')->get();
echo "Items after removing tenant scope: " . count($itemsAfterRemoval) . "\n";
// Cleanup
echo "\nCleaning up...\n";
$schema->dropTableIfExists('items');
$schema->dropTableIfExists('posts');
$schema->dropTableIfExists('users');
echo "✓ Done\n";