Skip to content
Merged

Wip #72

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
### Class: Rudra\Model\QB
| Visibility | Function |
|:-----------|:---------|
| public | `__construct( $dsn)`<br>Initializes the database driver based on the provided DSN or a default DSN from the container.<br>If no DSN is provided and none is available in the container, a LogicException is thrown.<br>The driver is selected based on the database type specified in the DSN's driver attribute.<br>-------------------------<br>Инициализирует драйвер базы данных на основе предоставленного DSN или DSN по умолчанию из контейнера.<br>Если DSN не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.<br>Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера DSN. |
| public | `__construct( $connection)`<br>Initializes the database driver based on the provided connection or a default connection from the container.<br>If no connection is provided and none is available in the container, a LogicException is thrown.<br>The driver is selected based on the database type specified in the connection's driver attribute.<br>-------------------------<br>Инициализирует драйвер базы данных на основе предоставленного connection или connection по умолчанию из контейнера.<br>Если connection не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.<br>Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера connection. |
| public | `select(string $fields): self`<br> |
| public | `concat(string $fieldName, string $alias, ?string $orderBy): self`<br> |
| public | `from(string $table): self`<br> |
Expand Down Expand Up @@ -116,11 +116,12 @@
### Class: Rudra\Model\Repository
| Visibility | Function |
|:-----------|:---------|
| public | `__construct(?string $table, ?PDO $dsn)`<br>Initializes the class with a table name, DSN (Data Source Name), and sets up dependencies.<br>The DSN is either provided directly or retrieved from the Rudra container.<br>If the DSN is not an instance of PDO, a LogicException is thrown.<br>-------------------------<br>Инициализирует класс с именем таблицы, DSN (Data Source Name) и настраивает зависимости.<br>DSN может быть предоставлен напрямую или извлечен из контейнера Rudra.<br>Если DSN не является экземпляром PDO, выбрасывается исключение LogicException. |
| public | `__construct(?string $table, ?PDO $connection)`<br>Initializes the class with a table name, connection, and sets up dependencies.<br>The connection is either provided directly or retrieved from the Rudra container.<br>If the connection is not an instance of PDO, a LogicException is thrown.<br>-------------------------<br>Инициализирует класс с именем таблицы, connection и настраивает зависимости.<br>connection может быть предоставлен напрямую или извлечен из контейнера Rudra.<br>Если connection не является экземпляром PDO, выбрасывается исключение LogicException. |
| public | `__call( $method, array $parameters)`<br>Handles calls to undefined methods by throwing a LogicException.<br>This method is invoked when an attempt is made to call a non-existent method on the object.<br>-------------------------<br>Обрабатывает вызовы неопределённых методов, выбрасывая исключение LogicException.<br>Этот метод вызывается, когда происходит попытка вызвать несуществующий метод у объекта. |
| public | `qb(): Rudra\Model\QB`<br>Returns an instance of the Query Builder (QB).<br>If the QB instance is not yet initialized, it creates a new instance using the DSN.<br>This method implements lazy initialization to ensure the QB instance is created only when needed.<br>-------------------------<br>Возвращает экземпляр Query Builder (QB).<br>Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием DSN.<br>Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. |
| public | `onDsn(PDO $dsn): self`<br>Sets the DSN (Data Source Name) for the database connection and resets the Query Builder instance.<br>This method allows changing the DSN dynamically and ensures that the Query Builder is re-initialized.<br>-------------------------<br>Устанавливает DSN (Data Source Name) для подключения к базе данных и сбрасывает экземпляр Query Builder.<br>Этот метод позволяет динамически изменять DSN и гарантирует повторную инициализацию Query Builder. |
| public | `withDsn(PDO $dsn): self`<br>Creates and returns a new instance of the class with the specified DSN.<br>This method allows changing the DSN while preserving the current table name.<br>It is useful for creating new instances with different database connections without modifying the original object.<br>-------------------------<br>Создает и возвращает новый экземпляр класса с указанным DSN.<br>Этот метод позволяет изменить DSN, сохраняя текущее имя таблицы.<br>Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. |
| public | `qb(): Rudra\Model\QB`<br>Returns an instance of the Query Builder (QB).<br>If the QB instance is not yet initialized, it creates a new instance using the connection.<br>This method implements lazy initialization to ensure the QB instance is created only when needed.<br>-------------------------<br>Возвращает экземпляр Query Builder (QB).<br>Если экземпляр QB ещё не инициализирован, создаётся новый экземпляр с использованием connection.<br>Этот метод реализует ленивую инициализацию, чтобы гарантировать создание экземпляра QB только при необходимости. |
| public | `connection(): PDO`<br>Returns the current PDO instance used by the repository.<br>-------------------------<br>Возвращает текущий экземпляр PDO, используемый репозиторием. |
| public | `onConnection(PDO $connection): self`<br>Sets the connection for the database connection and resets the Query Builder instance.<br>This method allows changing the connection dynamically and ensures that the Query Builder is re-initialized.<br>-------------------------<br>Устанавливает connection для подключения к базе данных и сбрасывает экземпляр Query Builder.<br>Этот метод позволяет динамически изменять connection и гарантирует повторную инициализацию Query Builder. |
| public | `withConnectionn(PDO $connection): self`<br>Creates and returns a new instance of the class with the specified connection.<br>This method allows changing the connection while preserving the current table name.<br>It is useful for creating new instances with different database connections without modifying the original object.<br>-------------------------<br>Создает и возвращает новый экземпляр класса с указанным connection.<br>Этот метод позволяет изменить connection, сохраняя текущее имя таблицы.<br>Он полезен для создания новых экземпляров с разными подключениями к базе данных без изменения исходного объекта. |
| public | `qBuilder( $queryString, array $queryParams): array`<br>Executes a custom SQL query and returns the result as an associative array.<br>The method prepares the query, executes it with optional parameters, and fetches all results.<br>-------------------------<br>Выполняет пользовательский SQL-запрос и возвращает результат в виде ассоциативного массива.<br>Метод подготавливает запрос, выполняет его с необязательными параметрами и извлекает все результаты. |
| public | `getAllPerPage(Rudra\Pagination $pagination, ?string $fields)`<br> |
| public | `find( $id): array\|false`<br> |
Expand All @@ -135,7 +136,7 @@
| protected static | `createStmtString(array $fields)`<br>Generates two strings for an SQL INSERT statement: one for column names and one for placeholders.<br>The method takes an array of fields and constructs two comma-separated lists:<br>- A list of column names.<br>- A list of placeholders (prefixed with colons) for parameter binding.<br>These strings can be directly used in the SQL INSERT query.<br>-------------------------<br>Генерирует две строки для SQL-запроса INSERT:<br>- Список имен столбцов.<br>- Список плейсхолдеров (с префиксом двоеточия) для связывания параметров.<br>Эти строки могут быть напрямую использованы в SQL-запросе INSERT. |
| public | `getColumns()`<br>Retrieves the column information for the current table based on the database driver.<br>The method executes a query specific to the database type (MySQL, PostgreSQL, or SQLite)<br>to fetch the column details of the table.<br>-------------------------<br>Получает информацию о столбцах текущей таблицы в зависимости от типа базы данных.<br>Метод выполняет запрос, специфичный для используемой СУБД (MySQL, PostgreSQL или SQLite),<br>чтобы получить сведения о столбцах таблицы. |
| public | `getFields(?string $fields)`<br>Retrieves the list of fields (columns) for the current table.<br>If no specific fields are provided, the method fetches all column names based on the database driver.<br>Otherwise, it splits the provided comma-separated string of fields into an array.<br>-------------------------<br>Получает список полей (столбцов) для текущей таблицы.<br>Если конкретные поля не указаны, метод извлекает все имена столбцов в зависимости от типа базы данных.<br>В противном случае он разделяет предоставленную строку полей, разделённых запятыми, на массив. |
| public | `search(string $search, string $column, ?string $fields)`<br>Searches for records in the database based on a search term and column.<br>The method prepares and executes a query to retrieve records where the specified column matches the search term.<br>Results are ordered by ID in descending order and limited to 10 records.<br>-------------------------<br>Выполняет поиск записей в базе данных на основе поискового запроса и указанного столбца.<br>Метод подготавливает и выполняет запрос для получения записей, где указанный столбец соответствует поисковому запросу.<br>Результаты сортируются по ID в порядке убывания и ограничиваются 10 записями. |
| public | `search(string $search, string $column, ?string $fields): array`<br>Searches for records in the database based on a search term and column.<br>The method prepares and executes a query to retrieve records where the specified column matches the search term.<br>Results are ordered by ID in descending order and limited to 10 records.<br>-------------------------<br>Выполняет поиск записей в базе данных на основе поискового запроса и указанного столбца.<br>Метод подготавливает и выполняет запрос для получения записей, где указанный столбец соответствует поисковому запросу.<br>Результаты сортируются по ID в порядке убывания и ограничиваются 10 записями. |
| public | `toggle()`<br> |
| public | `cache(array $params, $cacheTime)`<br>Caches the result of a method call to a JSON file for a specified duration.<br>If the cached file exists and is still valid (based on cache time), the cached data is returned.<br>Otherwise, the method executes the specified method, caches its result, and returns the data.<br>-------------------------<br>Кэширует результат вызова метода в JSON-файл на определённый период времени.<br>Если кэшированный файл существует и всё ещё действителен (на основе времени кэширования), возвращаются кэшированные данные.<br>В противном случае метод выполняет указанный метод, кэширует его результат и возвращает данные. |
| public | `clearCache(string $type)`<br>Clears cached files of a specified type or all types.<br>The method removes JSON cache files from the 'database' or 'view' directories,<br>or clears both directories if 'all' is specified.<br>-------------------------<br>Очищает кэшированные файлы указанного типа или всех типов.<br>Метод удаляет JSON-файлы кэша из директорий 'database' или 'view',<br>или очищает обе директории, если указано значение 'all'. |
Expand Down
24 changes: 12 additions & 12 deletions src/QB.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,26 @@ class QB
private string $query = '';

/**
* Initializes the database driver based on the provided DSN or a default DSN from the container.
* If no DSN is provided and none is available in the container, a LogicException is thrown.
* The driver is selected based on the database type specified in the DSN's driver attribute.
* Initializes the database driver based on the provided connection or a default connection from the container.
* If no connection is provided and none is available in the container, a LogicException is thrown.
* The driver is selected based on the database type specified in the connection's driver attribute.
* -------------------------
* Инициализирует драйвер базы данных на основе предоставленного DSN или DSN по умолчанию из контейнера.
* Если DSN не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.
* Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера DSN.
* Инициализирует драйвер базы данных на основе предоставленного connection или connection по умолчанию из контейнера.
* Если connection не предоставлен и отсутствует в контейнере, выбрасывается исключение LogicException.
* Драйвер выбирается на основе типа базы данных, указанного в атрибуте драйвера connection.
*
* @param $dsn
* @param $connection
* @throws LogicException
*/
public function __construct($dsn = null)
public function __construct($connection = null)
{
$dsn = $dsn ?? Rudra::get('DSN') ?? throw new LogicException("DSN is mot installed");
$connection = $connection ?? Rudra::get('connection') ?? throw new LogicException("connection is not installed");

if ($dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") {
if ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "mysql") {
$this->driver = new MySQL;
} elseif ($dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") {
} elseif ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "pgsql") {
$this->driver = new PgSQL;
} elseif ($dsn->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") {
} elseif ($connection->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlite") {
$this->driver = new SQLite;
}
}
Expand Down
Loading
Loading