Skip to content

Introduce db() Helper to Encapsulate Database DI Lookup #460

Description

@armanist

Introduce db() Helper to Encapsulate Database DI Lookup

Description

Across the Database and Model layer (specifically within TransactionTrait, RelationalTrait, MigrationManager, and ModelFactory), the Database::class is manually requested from the Dependency Injection container using this repetitive boilerplate:

if (!Di::isRegistered(Database::class)) {
    Di::register(Database::class);
}

$db = Di::get(Database::class); // usually chained with ->getOrmClass() or similar.

While the overall framework implements utility helpers (like config(), session(), view()) to cleanly proxy these exact DI resolutions, the Database module is entirely missing a db() helper!

As a result, domain traits and managers are bloated with raw container logic, violating the service locator pattern established by the rest of the application.

Proposed Solution

  1. Create the Helper: Introduce a file at src/Database/Helpers/db.php that exposes a db() function.
<?php

use Quantum\Database\Database;
use Quantum\Di\Di;

/**
 * Gets the Database service instance
 * @throws \Quantum\Di\Exceptions\DiException|\ReflectionException
 */
function db(): Database
{
    if (!Di::isRegistered(Database::class)) {
        Di::register(Database::class);
    }

    return Di::get(Database::class);
}
  1. Refactor Codebase: Go through TransactionTrait, RelationalTrait, MigrationManager, and ModelFactory and replace the verbose DI blocks with the clean helper call. For example, in TransactionTrait::resolveTransaction():
-        if (!Di::isRegistered(Database::class)) {
-            Di::register(Database::class);
-        }
-
-        $db = Di::get(Database::class)->getOrmClass();
+        $db = db()->getOrmClass();
  1. Update Autoloading: Ensure src/Database/Helpers/db.php is properly configured to be autoloaded (either via composer or the LoadHelpersStage).

  2. Unit Tests:

    • Create a corresponding tests/Unit/Database/Helpers/DbHelperTest.php file to explicitly test the new locator method.
    • Run the full test suite over the Database and Model modules to verify that RelationalTrait, TransactionTrait, MigrationManager and ModelFactory continue to operate identically under the rewritten backend logic.

Metadata

Metadata

Assignees

Labels

Fields

No fields configured for Feature.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions