PHP code example of monkeyscloud / monkeyslegion-database
1. Go to this page and download the library: Download monkeyscloud/monkeyslegion-database library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
monkeyscloud / monkeyslegion-database example snippets
use MonkeysLegion\Database\Connection\ConnectionManager;
// From a config array — the simplest setup
$manager = ConnectionManager::fromArray([
'default' => [
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => 3306,
'database' => 'myapp',
'username' => 'root',
'password' => 'secret',
],
]);
// Get the default connection (lazy — no PDO until first use)
$conn = $manager->connection();
// Execute queries
$conn->execute('INSERT INTO users (name) VALUES (:name)', [':name' => 'Alice']);
$stmt = $conn->query('SELECT * FROM users WHERE id = :id', [':id' => 1]);
$user = $stmt->fetch();
use MonkeysLegion\Database\Config\{DatabaseConfig, DsnConfig};
use MonkeysLegion\Database\Connection\Connection;
use MonkeysLegion\Database\Types\DatabaseDriver;
$dsn = new DsnConfig(
driver: DatabaseDriver::MySQL,
host: 'localhost',
port: 3306,
database: 'myapp',
);
$config = new DatabaseConfig(
name: 'primary',
driver: DatabaseDriver::MySQL,
dsn: $dsn,
username: 'root',
password: 'secret',
);
$conn = new Connection($config);
$conn->connect();
// PDO is available
$pdo = $conn->pdo();
$conn = $manager->connection(); // No database connection yet
echo $conn->getName(); // "default" — no connection needed
echo $conn->getDriver()->label(); // "MySQL / MariaDB" — still no connection
$conn->query('SELECT 1'); // NOW the connection is established
$conn->execute('INSERT INTO users (name) VALUES (:n)', [':n' => 'Alice']);
$id = $conn->lastInsertId(); // '1'
// PostgreSQL — pass the sequence name
$pgId = $conn->lastInsertId('users_id_seq');
use MonkeysLegion\Database\Support\RetryHandler;
use MonkeysLegion\Database\Support\RetryConfig;
$result = RetryHandler::withRetry(
operation: function () use ($conn): int {
return $conn->execute(
'UPDATE inventory SET stock = stock - 1 WHERE id = :id',
[':id' => 42],
);
},
config: new RetryConfig(
maxAttempts: 4,
baseDelayMs: 20,
multiplier: 2.0,
maxDelayMs: 500,
jitter: true,
),
);
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('db');
$log->pushHandler(new StreamHandler('php://stderr'));
// On ConnectionManager — set hook propagates to all open connections
$manager->logger = $log;
// On a single Connection directly
$conn->logger = $log;
use MonkeysLegion\Database\Contracts\ConnectionEventDispatcherInterface;
$manager->eventDispatcher = $myDispatcher; // propagates to all open connections
$conn->eventDispatcher = $myDispatcher; // or on a single connection