Bicycle/Services/Mongo/MongoDriver.php
Egor Isaev 9d4edf147a dev
2026-08-07 11:40:03 +03:00

68 lines
2.2 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description MongoDriver.php
* @copyright (c) 07/08/2026
*/
namespace Services\Mongo;
use MongoDB\Client;
use MongoDB\Collection;
use MongoDB\Database;
/**
* Обёртка над MongoDB\Client (пакет mongodb/mongodb, требует ext-mongodb).
* Использование классов MongoDB\* в сигнатурах ниже само по себе безопасно без
* расширения — PHP резолвит имя класса лениво, при реальном обращении к значению,
* а не при подключении файла. Единственное место, где расширение реально нужно —
* __construct(): new Client(...) упадёт в \Error, если ext-mongodb не установлен.
* Поэтому Mongo::instance() не вызывать эагерно из bootstrap/Core::init() —
* только там, где Mongo реально нужен.
*/
class MongoDriver
{
/** @var Client */
protected Client $_client;
/** @var string Имя БД по умолчанию (см. database()/collection()) */
protected string $_database;
/**
* @param array $config uri (например 'mongodb://mongo:27017'), database
*/
public function __construct(array $config)
{
$this->_client = new Client($config['uri'] ?? 'mongodb://localhost:27017');
$this->_database = $config['database'] ?? '';
}
/**
* @return Client
*/
public function client(): Client
{
return $this->_client;
}
/**
* @param string|null $name null — имя БД из конфига
* @return Database
*/
public function database(?string $name = null): Database
{
return $this->_client->selectDatabase($name ?? $this->_database);
}
/**
* @param string $name Имя коллекции
* @param string|null $database null — имя БД из конфига
* @return Collection
*/
public function collection(string $name, ?string $database = null): Collection
{
return $this->_client->selectCollection($database ?? $this->_database, $name);
}
}