Skip to content

Instantly share code, notes, and snippets.

Created October 26, 2018 18:12
What would you like to do?
Async MySQL
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(
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