Skip to content

Commit

Permalink
Consolidate database examples
Browse files Browse the repository at this point in the history
  • Loading branch information
dktapps committed Nov 21, 2023
1 parent ab80c54 commit 1ac228a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 214 deletions.
42 changes: 37 additions & 5 deletions examples/Databases.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ public function __construct(array $config){
public function run() : void{
//set up the connection for tasks to use
self::$connection = new PDO(...unserialize($this->config));
self::$connection->exec("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT)");
self::$connection->exec("INSERT INTO test (value) VALUES ('Hello world!')");
}

/**
Expand All @@ -45,6 +47,24 @@ public function run() : void{
public static function getConnection() : \PDO{ return self::$connection; }
}

class DBFetchTask extends Runnable{
private string $result;

public function run() : void{
$pdo = PDOWorker::getConnection();
$statement = $pdo->prepare("SELECT * FROM test");
$statement->execute();

//we're serializing here because fetchAll returns an array, which is not thread-safe
//you might not need to do this if your results are simple enough to be thread-safe
$this->result = serialize($statement->fetchAll());
}

public function getResult() : array{
return unserialize($this->result);
}
}

/*
* When the Pool starts new Worker threads, they will construct the
* PDO object before any Runnable tasks are executed.
Expand All @@ -56,11 +76,23 @@ public static function getConnection() : \PDO{ return self::$connection; }
*/

for($i = 0; $i < 10; $i++){
$pool->submit(new class extends Runnable{
public function run() : void{
var_dump(\PDOWorker::getConnection());
}
});
$pool->submit(new DBFetchTask());
}

/*
* Make sure to regularly call collect() on the pool, otherwise memory will be leaked.
* You can use collect() to fetch the results of tasks.
* If you don't care about the results, call collect() without a callback.
*/
while($pool->collect(function(Runnable $runnable) : bool{
if($runnable instanceof DBFetchTask){
var_dump($runnable->getResult());
}
return true; //returning false will stop the collection
}) > 0){
echo "Still waiting\n";
usleep(1_000_000);
//you probably don't want to do this in a loop in real code, as it will block until all tasks are finished
}

$pool->shutdown();
88 changes: 0 additions & 88 deletions examples/MySQLi.php

This file was deleted.

121 changes: 0 additions & 121 deletions examples/Pooling.php

This file was deleted.

0 comments on commit 1ac228a

Please sign in to comment.