Database connection
Database access in Laminas is handled by the laminas-db package. Its main object is the adapter: it holds the connection and runs queries. The connection parameters go into the configuration, and the adapter is created for you and is available in the service container.
Installation
composer require laminas/laminas-dbThe component installer asks which file to inject the Laminas\Db module into. Choose config/modules.config.php — a new line appears in the module list.
Connection parameters
Shared parameters go into config/autoload/global.php:
// config/autoload/global.php
return [
'db' => [
'driver' => 'Pdo_Mysql',
'hostname' => 'localhost',
'database' => 'blog',
'charset' => 'utf8mb4',
],
];| Key | Meaning |
|---|---|
driver | What to connect through: Pdo_Mysql, Pdo_Pgsql, Pdo_Sqlite |
hostname | The database server address |
database | The database name |
charset | The connection encoding |
The user name and password go into config/autoload/local.php, which stays out of the repository:
// config/autoload/local.php
return [
'db' => [
'username' => 'root',
'password' => 'secret',
],
];On startup both arrays are merged into one db section.
The posts table
Laminas has no migrations — files that describe tables in code. A table is created with an SQL query in any database tool (phpMyAdmin, the mysql console):
CREATE DATABASE blog CHARACTER SET utf8mb4;
USE blog;
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
body TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO posts (title, body) VALUES
('First post', 'The text of the first post.'),
('Second post', 'The text of the second post.');Save this query in the project, for example in data/schema.sql, so that the table can be recreated on another machine.
The adapter in the container
The Laminas\Db module registers the adapter under the name Laminas\Db\Adapter\AdapterInterface. A factory gets it like this:
use Laminas\Db\Adapter\AdapterInterface;
$adapter = $container->get(AdapterInterface::class);The connection is not opened at this moment but on the first query.
The first query
An SQL query is run with the query() method. Values are passed separately, in the second argument, and a question mark stands in their place in the query:
$rows = $adapter->query('SELECT id, title FROM posts WHERE id > ?', [0]);
foreach ($rows as $row) {
echo $row['title'];
}The loop prints the titles of both posts. In the next lesson this code moves into a separate class, and the controller receives ready objects.
Common mistake
If the package is installed but the Laminas\Db module did not get into config/modules.config.php, the container knows nothing about the adapter and throws a ServiceNotFoundException for Laminas\Db\Adapter\AdapterInterface. Open the module list and add the line 'Laminas\Db' by hand, before your own modules.