Created
January 10, 2022 11:14
-
-
Save mahmutbayri/4278c2b1c00c42f30b4c54af2c3a5d0a 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\MySQL\ConnectionInterface; | |
use React\MySQL\Factory; | |
use React\MySQL\QueryResult; | |
require_once __DIR__ . '/vendor/autoload.php'; | |
class QueryBuilder extends Builder | |
{ | |
/** | |
* @var ConnectionInterface | |
*/ | |
private $_connection; | |
public function query() | |
{ | |
return $this->_connection->query($this->toSql(), $this->getBindings()); | |
} | |
public function quit() | |
{ | |
$this->_connection->quit(); | |
} | |
public function queryStream($sql) | |
{ | |
$this->_connection->queryStream($sql); | |
} | |
public function setConnection(ConnectionInterface $connection) | |
{ | |
$this->_connection = $connection; | |
} | |
} | |
class QueryBuilderWrapper | |
{ | |
/** | |
* @var Factory | |
*/ | |
public $factory; | |
public function __construct($factory) | |
{ | |
$this->factory = $factory; | |
} | |
public function createLazyConnection($uri) | |
{ | |
$capsule = new Manager; | |
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->addConnection([ | |
'driver' => 'mysql', | |
'database' => $parts['path'], | |
]); | |
$builder = new QueryBuilder($capsule->getConnection()); | |
$builder->setConnection($this->factory->createLazyConnection($uri)); | |
return $builder; | |
} | |
} | |
$factory = new React\MySQL\Factory(); | |
$connection = (new QueryBuilderWrapper($factory))->createLazyConnection('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
It returns