-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path02-plugins.php
More file actions
276 lines (226 loc) · 7.77 KB
/
02-plugins.php
File metadata and controls
276 lines (226 loc) · 7.77 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
<?php
/**
* Example: Plugin System.
*
* Demonstrates how to create and use plugins to extend PdoDb functionality.
*
* Usage:
* php examples/31-plugins/01-plugin-examples.php
* PDODB_DRIVER=mysql php examples/31-plugins/01-plugin-examples.php
* PDODB_DRIVER=pgsql php examples/31-plugins/01-plugin-examples.php
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\PdoDb;
use tommyknocker\pdodb\plugin\AbstractPlugin;
use tommyknocker\pdodb\query\QueryBuilder;
use tommyknocker\pdodb\events\QueryExecutedEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
$db = createExampleDb();
$driver = getCurrentDriver($db);
echo "=== Plugin System Example (on $driver) ===\n\n";
// Create table using fluent API (cross-dialect)
$schema = $db->schema();
$schema->dropTableIfExists('products');
$schema->createTable('products', [
'id' => $schema->primaryKey(),
'name' => $schema->string(255)->notNull(),
'price' => $schema->decimal(10, 2)->notNull(),
'status' => $schema->string(50)->defaultValue('active'),
'category_id' => $schema->integer(),
'created_at' => $schema->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),
'deleted_at' => $schema->timestamp(),
]);
// Example 1: Simple Plugin with Macros
echo "1. Simple Plugin with Macros:\n";
echo " Registering plugin that adds query macros...\n\n";
class ProductMacrosPlugin extends AbstractPlugin
{
public function register(PdoDb $db): void
{
// Register macros for QueryBuilder
QueryBuilder::macro('active', function (QueryBuilder $query) {
return $query->where('status', 'active');
});
QueryBuilder::macro('wherePrice', function (QueryBuilder $query, string $operator, float $price) {
return $query->where('price', $price, $operator);
});
QueryBuilder::macro('recent', function (QueryBuilder $query, int $days = 7) {
$date = date('Y-m-d H:i:s', strtotime("-{$days} days"));
return $query->where('created_at', $date, '>=');
});
}
public function getName(): string
{
return 'product-macros';
}
}
$db->registerPlugin(new ProductMacrosPlugin());
// Insert test data
$db->find()->table('products')->insert([
'name' => 'Laptop',
'price' => 999.99,
'status' => 'active',
'category_id' => 1,
]);
$db->find()->table('products')->insert([
'name' => 'Phone',
'price' => 599.99,
'status' => 'active',
'category_id' => 1,
]);
$db->find()->table('products')->insert([
'name' => 'Tablet',
'price' => 299.99,
'status' => 'inactive',
'category_id' => 2,
]);
// Use macros
$activeProducts = $db->find()
->table('products')
->active()
->get();
echo " Active products: " . count($activeProducts) . "\n";
$expensiveProducts = $db->find()
->table('products')
->active()
->wherePrice('>', 500.00)
->get();
echo " Expensive active products (> \$500): " . count($expensiveProducts) . "\n\n";
// Example 2: Plugin with Scopes
echo "2. Plugin with Global Scopes:\n";
echo " Registering plugin that adds global scopes...\n\n";
class SoftDeletePlugin extends AbstractPlugin
{
public function register(PdoDb $db): void
{
// Register global scope that automatically filters deleted records
$db->addScope('notDeleted', function (QueryBuilder $query) {
return $query->whereNull('deleted_at');
});
}
public function getName(): string
{
return 'soft-delete';
}
}
$db->registerPlugin(new SoftDeletePlugin());
// Scope is automatically applied to all queries
$allProducts = $db->find()
->table('products')
->get();
echo " Products with soft-delete scope applied: " . count($allProducts) . "\n\n";
// Example 3: Plugin with Event Listeners
echo "3. Plugin with Event Listeners:\n";
echo " Registering plugin that listens to query events...\n\n";
$queryCount = 0;
$queryTimes = [];
class QueryMonitorPlugin extends AbstractPlugin
{
private int $queryCount;
private array $queryTimes;
public function __construct(int &$queryCount, array &$queryTimes)
{
$this->queryCount = &$queryCount;
$this->queryTimes = &$queryTimes;
}
public function register(PdoDb $db): void
{
$dispatcher = $db->getEventDispatcher();
if ($dispatcher !== null) {
$dispatcher->addListener(
QueryExecutedEvent::class,
function (QueryExecutedEvent $event) {
$this->queryCount++;
$this->queryTimes[] = $event->getExecutionTime();
}
);
}
}
public function getName(): string
{
return 'query-monitor';
}
}
// Set up event dispatcher
$dispatcher = new EventDispatcher();
$db->setEventDispatcher($dispatcher);
$db->registerPlugin(new QueryMonitorPlugin($queryCount, $queryTimes));
// Execute some queries
$db->find()->table('products')->get();
$db->find()->table('products')->where('status', 'active')->get();
echo " Queries monitored: $queryCount\n";
if (count($queryTimes) > 0) {
$avgTime = array_sum($queryTimes) / count($queryTimes);
echo " Average query time: " . round($avgTime * 1000, 2) . " ms\n";
}
echo "\n";
// Example 4: Complex Plugin with Multiple Features
echo "4. Complex Plugin with Multiple Features:\n";
echo " Registering plugin that combines macros, scopes, and events...\n\n";
class ECommercePlugin extends AbstractPlugin
{
public function register(PdoDb $db): void
{
// Macros
QueryBuilder::macro('featured', function (QueryBuilder $query) {
return $query->where('status', 'featured');
});
QueryBuilder::macro('inCategory', function (QueryBuilder $query, int $categoryId) {
return $query->where('category_id', $categoryId);
});
// Scopes
$db->addScope('available', function (QueryBuilder $query) {
return $query->where('status', 'active')
->whereNull('deleted_at');
});
// Event listeners (if dispatcher is available)
$dispatcher = $db->getEventDispatcher();
if ($dispatcher !== null) {
$dispatcher->addListener(
QueryExecutedEvent::class,
function (QueryExecutedEvent $event) {
// Log slow queries (example)
if ($event->getExecutionTime() > 0.1) {
error_log("Slow query detected: " . substr($event->getSql(), 0, 50));
}
}
);
}
}
public function getName(): string
{
return 'ecommerce';
}
}
$db->registerPlugin(new ECommercePlugin());
// Use all features
$featuredProducts = $db->find()
->table('products')
->featured()
->inCategory(1)
->get();
echo " Featured products in category 1: " . count($featuredProducts) . "\n\n";
// Example 5: Plugin Management
echo "5. Plugin Management:\n";
echo " Managing registered plugins...\n\n";
// Check if plugin is registered
if ($db->hasPlugin('product-macros')) {
echo " ✓ 'product-macros' plugin is registered\n";
}
// Get plugin instance
$plugin = $db->getPlugin('product-macros');
if ($plugin !== null) {
echo " ✓ Retrieved plugin: " . $plugin->getName() . "\n";
}
// Get all plugins
$plugins = $db->getPlugins();
echo " Registered plugins: " . count($plugins) . "\n";
foreach ($plugins as $name => $pluginInstance) {
echo " - $name\n";
}
// Unregister plugin (macros remain registered)
$db->unregisterPlugin('product-macros');
echo " ✓ Unregistered 'product-macros' plugin\n";
echo " Macros still work (they remain registered): " . (QueryBuilder::hasMacro('active') ? 'Yes' : 'No') . "\n";
echo "\n=== Plugin System Example Complete ===\n";