joomla/database
Joomla Database provides a generic database layer and drivers for building queries and managing connections. Includes a factory for creating drivers, and helpers for safe input handling (escape/quote), making it easier to integrate database access in custom PHP apps.
Start by installing via Composer: composer require joomla/database. Then instantiate a database driver using Database\DatabaseFactory (not singleton getInstance(), which is deprecated and removed in v5+). Use the factory’s getDriver() method with connection options (host, user, password, port, database, etc.) to obtain a driver instance (e.g., MySQL, PostgreSQL). For basic queries, use $db->setQuery($query)->load*() or execute() methods. For safe string handling, use $db->quote() or shorthand $db->q()—never concatenate raw user input into SQL. For iterative result handling, wrap result objects with DatabaseIterator to iterate or count results.
Use DatabaseQuery builders (e.g., $db->select()->from()->where()) to construct safe, portable queries. Prefer parameterized queries via where('id = :id', ['id' => 5]) over manual escaping. For reuse, extract query construction into services or repositories. Leverage castAs('CHAR', $value) instead of deprecated castAsChar. Use e, q, and qn shorthands (escape, quote, quoteName) for brevity—especially inside loops or mass operations. Integrate logging via PSR-3-compatible loggers using QueryMonitorInterface implementations (legacy setLogger() is deprecated); custom monitors can log SQL for debugging or auditing. Use union queries via $query->union($otherQuery) (not unionAll or unionDistinct), and ensure subqueries use alias() on from() or join() instead of passing aliases as parameters.
⚠️ Avoid deprecated patterns: getInstance() (use factory), getQuery(true) (use createQuery()), castAsChar, legacy setDebug() (replaced by monitors).
⚠️ Escape logic matters: Use escape($str, true) for LIKE wildcards and quote($escapedStr, false) to avoid double-escaping. For arrays, pass directly to quote().
⚠️ Driver-specific caveats: MySQL requires charset option in options array (e.g., 'charset' => 'utf8mb4') for proper encoding. PostgreSQL requires sslmode and certificate paths for secure connections.
✅ Extendability tip: Implement custom query monitors (QueryMonitorInterface) to track execution time, log slow queries, or enrich logs with context (e.g., request ID).
✅ Testing: Mock DatabaseDriver using its interfaces; unit test queries by asserting __toString() output and parameter binding.
✅ Migrations: When upgrading across versions (v3→v4), ensure PHP 8.3+ compatibility—especially removal of setQuery()’s legacy signature and stricter type enforcement in join()/from().
🔍 Debugging: Enable logging with a PSR-3 logger + LogLevel::DEBUG and inspect logged sql context. For failed queries, check stack traces in context to isolate source.
How can I help you explore Laravel packages today?