Two data contexts and shared reading: keeping catalogues separate

Two named adapters in one Symfony application read separate MySQL schemas, with explicit bindings, context checks, and neutral source-failure responses.

One shape, two independent worlds.
One shape, two independent worlds.

Two websites can install the same package for reading articles while holding completely different catalogs. A shared class version defines how a query behaves. It does not decide whose data that query will reach.

The distinction becomes visible when both catalogs contain an article numbered 7. In the coastal journal it is Tide notebook; in the forest journal it is Fern notebook. If a check only looks for a successful HTTP response, a connection to the neighboring database can appear perfectly healthy. The content and the reading context need checking as well.

Continue one article_demo on Symfony 8.1 and PHP 8.4+. Two named adapters read separate synthetic MySQL 8.4 schemas through native PDO in one Kernel. The tables use InnoDB. This composition checks correct source selection, rather than two independent installations or isolation of server access privileges.

The same number, different articles

Coast responds through /catalogue-demo/coast/{id} and Forest through /catalogue-demo/forest/{id}. Each adapter receives a separate PDO connection to its configured MySQL schema. Both profiles share one vendor directory and Kernel; a local file path no longer selects the catalogue.

Local ID coast catalog forest catalog
7 Tide notebook, published Fern notebook, published
11 Harbor log, published Absent
22 Absent Trail log, published
99 Coast draft, hidden Forest draft, hidden

The matching numbers are deliberate. They help expose a catalog substitution that would still produce a successful response. Articles present in only one site check a different mistake: accidentally widening a search to every available store.

In this model, a number has meaning within the selected catalog. If links later need to cross between sites, a separate contract must include their context or another globally defined key. A convenient local number does not become a global identity when a shared package is installed.

The shared module supplies behaviour; composition supplies the connection

The src/SiteCatalog module contains the shared SiteCatalog, the CatalogReader interface, and CoastCatalog/ForestCatalog adapters. Named bindings choose an adapter for each controller; the catalogue.coast_reader and catalogue.forest_reader services supply separate PDO connections from trusted MySQL configuration. The bindings below complement those services rather than configuring connections themselves. Add the entries under the existing services:, preserving the file and earlier routes. This does not install a local package into two skeletons.

services:
    App\SiteCatalog\CoastCatalog: ~
    App\SiteCatalog\ForestCatalog: ~
    App\SiteCatalog\CatalogReader $coastCatalog: '@App\SiteCatalog\CoastCatalog'
    App\SiteCatalog\CatalogReader $forestCatalog: '@App\SiteCatalog\ForestCatalog'
    App\Controller\CoastCatalogueController: ~
    App\Controller\ForestCatalogueController: ~
    App\Command\InitializeCataloguesCommand: ~

A wrong connection should stop the read

A separate schema alone is insufficient: configuration can be copied incorrectly. Each catalogue therefore contains a site_context table with one record. Before every read, the adapter calls SiteCatalog::open(), which checks the marker against the expected coast or forest key. A missing, extra, or mismatched record stops the read.

The complete teaching class is small:

<?php

declare(strict_types=1);

namespace App\SiteCatalog;

/**
 * Identity guard plus a server-enforced read-only session default.
 * This is not an immutable connection or a replacement for SQL account grants.
 */
final class SiteCatalog implements CatalogReader
{
    private function __construct(private readonly \PDO $database)
    {
    }

    public static function connection(string $dsn, string $user, string $password, bool $readOnly = true): \PDO
    {
        if (!str_starts_with($dsn, 'mysql:')) {
            throw new \InvalidArgumentException('A configured MySQL DSN is required.');
        }

        try {
            $database = new \PDO($dsn, $user, $password, [
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                \PDO::ATTR_EMULATE_PREPARES => false,
                \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                \PDO::ATTR_TIMEOUT => 5,
            ]);
            if ($readOnly) {
                $database->exec('SET SESSION TRANSACTION READ ONLY');
            }

            return $database;
        } catch (\PDOException $error) {
            throw new CatalogUnavailable('Configured catalog cannot be opened for this site.', previous: $error);
        }
    }

    public static function open(\PDO $database, string $expectedSite): self
    {
        if (preg_match('/\A[a-z][a-z0-9-]{0,31}\z/', $expectedSite) !== 1) {
            throw new \InvalidArgumentException('Invalid configured site key.');
        }

        try {
            if ($database->getAttribute(\PDO::ATTR_DRIVER_NAME) !== 'mysql' || $database->inTransaction()) {
                throw new \LogicException('An idle native MySQL reader connection is required.');
            }
            $database->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $database->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
            $database->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
            $database->exec('SET SESSION TRANSACTION READ ONLY');
            $statement = $database->query('SELECT singleton, site_key FROM site_context');
            try {
                $identity = $statement->fetch();
                $extra = $statement->fetch();
            } finally {
                $statement->closeCursor();
            }

            if ($identity === false || $extra !== false
                || (int) $identity['singleton'] !== 1 || $identity['site_key'] !== $expectedSite) {
                throw new CatalogUnavailable('Configured catalog identity does not match.');
            }

            return new self($database);
        } catch (\Throwable $error) {
            throw new CatalogUnavailable('Configured catalog cannot be opened for this site.', previous: $error);
        }
    }

    public function read(int $id): ?array
    {
        if ($id < 1) {
            throw new \InvalidArgumentException('A positive local identifier is required.');
        }

        try {
            $statement = $this->database->prepare('SELECT id, title FROM notes WHERE id = :id AND published = 1');
            try {
                $statement->bindValue(':id', $id, \PDO::PARAM_INT);
                $statement->execute();
                $row = $statement->fetch();

                return $row === false ? null : ['id' => (int) $row['id'], 'title' => $row['title']];
            } finally {
                $statement->closeCursor();
            }
        } catch (\Throwable $error) {
            throw new CatalogUnavailable('Configured catalog cannot be read.', previous: $error);
        }
    }
}

A missing schema or table causes an error instead of creating an empty catalogue. The class requires a native MySQL PDO connection with no active transaction, disables emulated prepared statements, and sets SET SESSION TRANSACTION READ ONLY. This is a server-enforced session transaction default, not an immutable connection property or a substitute for SQL grants. The driver is described in the PHP manual. The read query also selects only published = 1 and returns a defined set of fields; the HTTP reader neither creates tables nor seeds data.

The marker detects a specific assembly mistake: giving the coast adapter a schema marked forest. It does not authenticate data origin or verify that the SQL account belongs to the intended site. An actor allowed to change the table or configuration can substitute this context as well. The check before a read is not continuous monitoring of administrative changes and does not block them.

A hidden article must also remain unavailable. The correct site and connection do not imply that every row is suitable for public reading. The visibility rule is deliberately simple here; a more complex product needs its own access contract.

A request cannot select a neighboring site

Controllers accept a local ID and reject every query parameter with 400. The X-Site header does not select another adapter. Profile routes differ; the example establishes neither host isolation nor separate processes.

Check Behaviour
ID 7 through both routes 200 and different correct titles
ID available only in the other catalogue 404 without searching the neighbouring schema
Hidden or unknown ID 404
Query site or database 400
Missing, foreign, or broken catalogue Neutral 503 response

PDO/MySQL connection errors, context-check failures, and reading errors are normalized as CatalogUnavailable. A source failure does not become an empty result or successful fallback; the HTTP response remains a neutral 503.

Where this boundary ends

Two catalogues in one process do not prove that the process technically cannot connect to its neighbour’s schema. SQL accounts, database grants, and network access require separate checks. Give HTTP readers only the required read privileges on their respective catalogues, without CREATE, ALTER, or DROP; do not provide the separate migrator credentials to runtime readers. The context marker detects a composition error without authenticating data origin.

Caching and background work would also need keys with sufficient context. This example has neither a cache nor a queue and does not test their isolation.

Checking two profiles

Use PHP 8.4+, the PDO MySQL extension, MySQL 8.4, and the dependencies of the existing Symfony 8.1 project. Prepare two separate schemas in advance, configuring a reader connection and a separate migrator connection for each. The HTTP services catalogue.coast_reader and catalogue.forest_reader must use reader credentials. Perform initial table creation explicitly through the migrator, not through an HTTP request. After configuration, run from the project root:

File config/services.mysql_catalogue.yaml:

services:
    catalogue.coast_reader:
        class: PDO
        factory: ['App\SiteCatalog\SiteCatalog', 'connection']
        arguments:
            $dsn: '%env(CATALOGUE_COAST_DSN)%'
            $user: '%env(CATALOGUE_COAST_USER)%'
            $password: '%env(CATALOGUE_COAST_PASSWORD)%'

    catalogue.forest_reader:
        class: PDO
        factory: ['App\SiteCatalog\SiteCatalog', 'connection']
        arguments:
            $dsn: '%env(CATALOGUE_FOREST_DSN)%'
            $user: '%env(CATALOGUE_FOREST_USER)%'
            $password: '%env(CATALOGUE_FOREST_PASSWORD)%'

    catalogue.coast_migrator:
        class: PDO
        factory: ['App\SiteCatalog\SiteCatalog', 'connection']
        arguments:
            $dsn: '%env(CATALOGUE_COAST_DSN)%'
            $user: '%env(CATALOGUE_COAST_MIGRATOR_USER)%'
            $password: '%env(CATALOGUE_COAST_MIGRATOR_PASSWORD)%'
            $readOnly: false

    catalogue.forest_migrator:
        class: PDO
        factory: ['App\SiteCatalog\SiteCatalog', 'connection']
        arguments:
            $dsn: '%env(CATALOGUE_FOREST_DSN)%'
            $user: '%env(CATALOGUE_FOREST_MIGRATOR_USER)%'
            $password: '%env(CATALOGUE_FOREST_MIGRATOR_PASSWORD)%'
            $readOnly: false

For a local run, create a separate empty schema and two distinct accounts as a MySQL administrator. Replace the placeholders with your own values. The HTTP reader has SELECT only; supply the migrator only to a separate initialization process. Save runtime variables in untracked .env.local. This example does not transfer data from old SQLite files.

CREATE DATABASE demo_coast CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
CREATE USER 'demo_coast_r'@'127.0.0.1' IDENTIFIED BY '<runtime-password>';
CREATE USER 'demo_coast_m'@'127.0.0.1' IDENTIFIED BY '<migrator-password>';
GRANT SELECT ON demo_coast.* TO 'demo_coast_r'@'127.0.0.1';
GRANT CREATE, ALTER, INDEX, REFERENCES, SELECT, INSERT, UPDATE, DELETE, TRIGGER ON demo_coast.* TO 'demo_coast_m'@'127.0.0.1';
CATALOGUE_COAST_DSN="mysql:host=127.0.0.1;port=3306;dbname=demo_coast;charset=utf8mb4"
CATALOGUE_COAST_USER=demo_coast_r
CATALOGUE_COAST_PASSWORD="<runtime-password>"

For a local run, create a separate empty schema and two distinct accounts as a MySQL administrator. Replace the placeholders with your own values. The HTTP reader has SELECT only; supply the migrator only to a separate initialization process. Save runtime variables in untracked .env.local. This example does not transfer data from old SQLite files.

CREATE DATABASE demo_forest CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
CREATE USER 'demo_forest_r'@'127.0.0.1' IDENTIFIED BY '<runtime-password>';
CREATE USER 'demo_forest_m'@'127.0.0.1' IDENTIFIED BY '<migrator-password>';
GRANT SELECT ON demo_forest.* TO 'demo_forest_r'@'127.0.0.1';
GRANT CREATE, ALTER, INDEX, REFERENCES, SELECT, INSERT, UPDATE, DELETE, TRIGGER ON demo_forest.* TO 'demo_forest_m'@'127.0.0.1';
CATALOGUE_FOREST_DSN="mysql:host=127.0.0.1;port=3306;dbname=demo_forest;charset=utf8mb4"
CATALOGUE_FOREST_USER=demo_forest_r
CATALOGUE_FOREST_PASSWORD="<runtime-password>"
read -r -p 'Migrator user: ' CATALOGUE_COAST_MIGRATOR_USER
read -r -s -p 'Migrator password: ' CATALOGUE_COAST_MIGRATOR_PASSWORD
printf '
'
export CATALOGUE_COAST_MIGRATOR_USER CATALOGUE_COAST_MIGRATOR_PASSWORD
read -r -p 'Migrator user: ' CATALOGUE_FOREST_MIGRATOR_USER
read -r -s -p 'Migrator password: ' CATALOGUE_FOREST_MIGRATOR_PASSWORD
printf '
'
export CATALOGUE_FOREST_MIGRATOR_USER CATALOGUE_FOREST_MIGRATOR_PASSWORD
php bin/console app:catalogue-demo:init
unset CATALOGUE_COAST_MIGRATOR_USER CATALOGUE_COAST_MIGRATOR_PASSWORD CATALOGUE_FOREST_MIGRATOR_USER CATALOGUE_FOREST_MIGRATOR_PASSWORD

The explicit initializer creates teaching tables only when both are absent from an already configured schema. It preserves an existing catalogue with the correct marker and accessible expected columns, leaves its articles untouched, and refuses to modify an incomplete or foreign catalogue. Cooperating initializers are serialized with an advisory lock. DDL creates InnoDB tables with CHECK constraints for the singleton and visibility; the site key is VARCHAR(32) with utf8mb4_0900_bin, and the title is LONGTEXT. All DDL precedes a separate seed transaction: this is not an atomic schema upgrade, and failed DDL can leave a partial catalogue that a later invocation refuses to overwrite. There is no automatic migration of old SQLite files. Checks on actual MySQL cover correct content from both HTTP profiles, marker mismatch, existing-data preservation, and query failure with a neutral 503. This evidence concerns one Kernel with separate native connections, not isolation of server privileges or separate installations.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/SiteCatalog
  1. Editorial Stable content identity: Content ID, slug, revision and DB ID
  2. Symfony Core Errors, empty results and missing records: three application responses
  3. Symfony Core Two profiles, one contract: testing the boundary of reuse
  4. Symfony Core Independent sites with a shared Symfony foundation

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article