Created
January 10, 2022 13:22
-
-
Save mahmutbayri/44e35fa110148665d6f11229ee83427d to your computer and use it in GitHub Desktop.
This file contains 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 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result is