nixphp/database

NixPHP Database Plugin to work with various storage solutions.

Installs: 4

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:nixphp-plugin

dev-main 2025-05-25 20:11 UTC

This package is auto-updated.

Last update: 2025-05-25 20:11:41 UTC


README

Logo

NixPHP Database Plugin

← Back to NixPHP

nixphp/database

Simple, native PDO connection for your NixPHP application.

This plugin provides a shared PDO instance via the service container, supporting both MySQL/MariaDB and SQLite out of the box — with sensible defaults.

🧩 Part of the official NixPHP plugin collection. Install it when you need a native, PSR-compliant database connection — and nothing more.

📦 Features

  • ✅ Shared PDO instance, ready to use
  • ✅ MySQL/MariaDB and SQLite support
  • ✅ Uses sane defaults (error mode, fetch mode, UTF-8 charset)
  • ✅ Works with memory databases (sqlite::memory:)
  • ✅ Available via database() helper or DI container

📥 Installation

composer require nixphp/database

Then add the following configuration to /app/config.php. You can choose between MySQL/MariaDB or SQLite.

Example: MySQL

<?php

return [
    // ...
    'database' => [
        'driver'   => 'mysql',
        'host'     => '127.0.0.1',
        'database' => 'myapp',
        'username' => 'root',
        'password' => '',
        'charset'  => 'utf8mb4',
    ]
];

Example: SQLite

<?php

return [
    // ...
    'database' => [
        'driver'   => 'sqlite',
        'database' => __DIR__ . '/../storage/database.sqlite',
    ]
];

Or for in-memory SQLite:

return [
    // ...
    'database' => [
        'driver'   => 'sqlite',
        'database' => ':memory:',
    ]
];

🚀 Usage

Access the PDO instance globally via:

$pdo = database();

Or retrieve it manually from the service container:

$pdo = app()->container()->get('database');

Use it as usual with native PDO:

$stmt = database()->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$user = $stmt->fetch(); // default: FETCH_ASSOC

⚙️ Defaults applied

The PDO instance comes with these options:

[
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]

🔍 Internals

  • Loads config from /app/config/database.php
  • Builds DSN based on a given driver (mysql, sqlite)
  • Wraps PDO creation in a factory, handles exceptions gracefully
  • Registers database in the container and provides the database() helper

✅ Requirements

  • nixphp/framework >= 1.0

📄 License

MIT License.