Initial Version
This commit is contained in:
97
core/lib/Db/DataStore.php
Normal file
97
core/lib/Db/DataStore.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace KTXC\Db;
|
||||
|
||||
use DI\Attribute\Inject;
|
||||
|
||||
/**
|
||||
* DataStore provides access to MongoDB database operations
|
||||
* Uses composition pattern with Database wrapper
|
||||
*/
|
||||
class DataStore
|
||||
{
|
||||
protected array $configuration;
|
||||
protected Client $client;
|
||||
protected Database $database;
|
||||
|
||||
public function __construct(#[Inject('database')] array $configuration = [])
|
||||
{
|
||||
$this->configuration = $configuration;
|
||||
|
||||
$uri = $configuration['uri'];
|
||||
$databaseName = $configuration['database'];
|
||||
$options = $configuration['options'] ?? [];
|
||||
$driverOptions = $configuration['driverOptions'] ?? [];
|
||||
|
||||
$this->client = new Client($uri, $options, $driverOptions);
|
||||
$this->database = $this->client->selectDatabase($databaseName, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a collection from the database
|
||||
*
|
||||
* @param string $collectionName Collection name
|
||||
* @param array $options Collection options
|
||||
* @return Collection
|
||||
*/
|
||||
public function selectCollection(string $collectionName, array $options = []): Collection
|
||||
{
|
||||
return $this->database->selectCollection($collectionName, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying Database instance
|
||||
*/
|
||||
public function getDatabase(): Database
|
||||
{
|
||||
return $this->database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Client instance
|
||||
*/
|
||||
public function getClient(): Client
|
||||
{
|
||||
return $this->client;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all collections
|
||||
*/
|
||||
public function listCollections(array $options = []): array
|
||||
{
|
||||
return $this->database->listCollections($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a collection
|
||||
*/
|
||||
public function createCollection(string $collectionName, array $options = []): Collection
|
||||
{
|
||||
return $this->database->createCollection($collectionName, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a collection
|
||||
*/
|
||||
public function dropCollection(string $collectionName, array $options = []): array|object
|
||||
{
|
||||
return $this->database->dropCollection($collectionName, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get database name
|
||||
*/
|
||||
public function getDatabaseName(): string
|
||||
{
|
||||
return $this->database->getDatabaseName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic method to access collection as property
|
||||
*/
|
||||
public function __get(string $collectionName): Collection
|
||||
{
|
||||
return $this->selectCollection($collectionName);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user