Skip to content

Commit 3544013

Browse files
committed
The definition of a virtual table can now be given as a closure, which is lazy evaluated
1 parent f081e5c commit 3544013

File tree

3 files changed

+19
-13
lines changed

3 files changed

+19
-13
lines changed

doc/virtual-tables.md

+7-5
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ $vt1 = $db->select()
1111
->field('a.field1')
1212
->from('a', 'tableA');
1313

14-
$vt2 = $db->select()
15-
->field('a.field1')
16-
->from('a', 'tableA');
17-
1814
$db->getVirtualTables()->add('virt_table1', $vt1);
19-
$db->getVirtualTables()->add('virt_table2', $vt2);
15+
16+
// Lazy evaluated
17+
$db->getVirtualTables()->add('virt_table2', function () {
18+
return $db->select()
19+
->field('a.field1')
20+
->from('a', 'tableA');
21+
});
2022
```
2123

2224
Then use it as needed:

src/Tools/VirtualTables.php

+7-3
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ class VirtualTables {
99

1010
/**
1111
* @param string $tableName
12-
* @param Select $select
12+
* @param Select|\Closure $select
1313
* @return $this
1414
*/
15-
public function add($tableName, Select $select) {
15+
public function add($tableName, $select) {
1616
$this->virtualTables[$tableName] = $select;
1717
return $this;
1818
}
@@ -31,7 +31,11 @@ public function has($tableName) {
3131
*/
3232
public function get($tableName) {
3333
if($this->has($tableName)) {
34-
return $this->virtualTables[$tableName];
34+
$table = $this->virtualTables[$tableName];
35+
if($table instanceof \Closure) {
36+
return call_user_func($table);
37+
}
38+
return $table;
3539
}
3640
return null;
3741
}

tests/Builder/SelectTest.php

+5-5
Original file line numberDiff line numberDiff line change
@@ -347,13 +347,13 @@ public function testVirtualTables() {
347347
->field('a.field1')
348348
->from('a', 'tableA');
349349

350-
$vt2 = TestSelect::create()
351-
->field('a.field1')
352-
->from('a', 'tableA');
353-
354350
$db = new TestDB();
355351
$db->getVirtualTables()->add('virt_table1', $vt1);
356-
$db->getVirtualTables()->add('virt_table2', $vt2);
352+
$db->getVirtualTables()->add('virt_table2', function () {
353+
return TestSelect::create()
354+
->field('a.field1')
355+
->from('a', 'tableA');
356+
});
357357

358358
$query = TestSelect::create($db)
359359
->field('t.field1')

0 commit comments

Comments
 (0)