Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mahmutbayri/44e35fa110148665d6f11229ee83427d to your computer and use it in GitHub Desktop.
Save mahmutbayri/44e35fa110148665d6f11229ee83427d to your computer and use it in GitHub Desktop.
<?php
use Illuminate\Database\Capsule\Manager;
use Illuminate\Database\Query\Builder;
use React\EventLoop\Loop;
use React\MySQL\ConnectionInterface;
use React\MySQL\Factory;
use React\MySQL\Io\LazyConnection;
use React\MySQL\QueryResult;
require_once __DIR__ . '/vendor/autoload.php';
class CustomBuilder extends Builder
{
/**
* @var ConnectionInterface
*/
protected $lazyConnection;
public function setLazyConnection(ConnectionInterface $lazyConnection)
{
$this->lazyConnection = $lazyConnection;
return $this;
}
public function query()
{
return $this->lazyConnection->query($this->toSql(), $this->getBindings());
}
public function quit()
{
$this->lazyConnection->quit();
}
public function queryStream($sql)
{
$this->lazyConnection->queryStream($sql);
}
}
class MyFactory extends Factory
{
public function createLazyConnectionWithQueryBuilder($uri)
{
if (strpos($uri, '://') === false) {
$uri = 'mysql://' . $uri;
}
$parts = parse_url($uri);
$dbName = isset($parts['path']) ? rawurldecode(ltrim($parts['path'], '/')) : null;
if (is_null($dbName)) {
return \React\Promise\reject(new \InvalidArgumentException(
'Invalid Database name'
));
}
$capsule = new Manager();
$capsule->addConnection([
'driver' => 'mysql',
'database' => $dbName,
]);
$connection = new LazyConnection($this, $uri, Loop::get());
return (new CustomBuilder($capsule->getConnection()))
->setLazyConnection($connection);
}
}
$factory = new MyFactory();
$connection = $factory->createLazyConnectionWithQueryBuilder('homestead:secret@localhost/homestead');
$connection
->from('test_table')
->where('id', 1)
->query()
->then(
function (QueryResult $command) {
print_r($command->resultRows);
echo count($command->resultRows) . ' row(s) in set' . PHP_EOL;
},
function (Exception $error) {
echo 'Error: ' . $error->getMessage() . PHP_EOL;
}
);
$connection->quit();
@mahmutbayri
Copy link
Author

The result is


Array
(
    [0] => Array
        (
            [id] => 1
            [title] => react php
        )

)
1 row(s) in set

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment