Created
October 26, 2018 18:12
-
-
Save mnapoli/f935375c9dcd25327c47d6dffb629d4a to your computer and use it in GitHub Desktop.
Async MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use ProxyManager\Factory\LazyLoadingValueHolderFactory; | |
use ProxyManager\Proxy\ProxyInterface; | |
require_once __DIR__ . '/vendor/autoload.php'; | |
$mysql = mysqli_connect('localhost', 'root', '', 'example'); | |
$factory = new LazyLoadingValueHolderFactory(); | |
// Call the repository to get an entity | |
$foo = getFoo(); | |
var_dump($foo instanceof Foo); // true | |
var_dump($foo instanceof ProxyInterface); // true | |
var_dump($foo->isProxyInitialized()); // false | |
var_dump($foo->getBar()); // 6 | |
var_dump($foo->isProxyInitialized()); // true | |
function getFoo() | |
{ | |
global $mysql, $factory; | |
// Run the query asynchronously (doesn't wait for it to finish) | |
$mysql->query('select count(*) as `count` from activites', MYSQLI_ASYNC); | |
// Return a proxy to our model | |
return $factory->createProxy( | |
Foo::class, | |
function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) use ($mysql) { | |
// Wait for the query to be finished | |
$result = $mysql->reap_async_query(); | |
$row = $result->fetch_assoc(); | |
// Instantiate the model | |
$wrappedObject = new Foo($row['count']); | |
$initializer = null; | |
} | |
); | |
} | |
// The entity | |
class Foo | |
{ | |
private $bar; | |
public function __construct(int $bar) | |
{ | |
$this->bar = $bar; | |
} | |
public function getBar(): int | |
{ | |
return $this->bar; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment