Skip to content

Instantly share code, notes, and snippets.

@mnapoli
Created October 26, 2018 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnapoli/f935375c9dcd25327c47d6dffb629d4a to your computer and use it in GitHub Desktop.
Save mnapoli/f935375c9dcd25327c47d6dffb629d4a to your computer and use it in GitHub Desktop.
Async MySQL
<?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