---
title: "Container Project"
description: "Derafu Container"
type: "docs"
category: "doc"
tags: [php]
authors: [Anonymous]
date: "2026-11-15"
last_update: "2026-11-15"
time_minutes: 1
draft: false
unlisted: false
url: "https://www.derafu.dev/docs/data/container"
---

# Derafu Container



---

## Introduction

Specialized PHP data containers, from simple bags to stores validated with JSON Schema, with a common interface and typed array readers

# Flexible Data Containers for PHP

[![GitHub](https://img.shields.io/badge/github-derafu%2Fcontainer-blue?logo=github)](https://github.com/derafu/container)
![GitHub last commit](https://img.shields.io/github/last-commit/derafu/container/main)
![CI Workflow](https://github.com/derafu/container/actions/workflows/ci.yml/badge.svg?branch=main&amp;event=push)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/derafu/container)
![GitHub Issues](https://img.shields.io/github/issues-raw/derafu/container)
![Total Downloads](https://poser.pugx.org/derafu/container/downloads)
![Monthly Downloads](https://poser.pugx.org/derafu/container/d/monthly)

A collection of specialized PHP data containers that provide different levels of structure and validation, from simple bags to schema-validated stores.

## Features

- 🎯 Purpose-built containers for different needs.
- 🔍 Validation with a simple schema (`Vault`) or with JSON Schema (`Store`).
- 🛡️ Validation on every change: a container never holds data that breaks its schema.
- 🔤 Typed readers through `getReader()`, with validation and explicit conversions understood by PHPStan.
- 📦 Simple to complex data structures, with dot notation.
- 🔄 Sequential data handling.
- 🧩 Common interface across containers.
- 🌐 Translatable exceptions.
- 🪶 Minimal dependencies.
- 🧪 Comprehensive test coverage.

## Why Derafu\Container?

Unlike generic data structures, Derafu\Container provides specialized containers each designed for specific use cases:

- **Bag**: Simple, flexible data storage without restrictions.
- **Vault**: Structured data validated with a simple schema (types, required keys, choices, defaults, normalizers).
- **Store**: Structured data validated with JSON Schema.
- **Journal**: Sequential data storage with LIFO access.

All of them share the same interface, so code that reads data does not care which container it received.

## Installation

Install via Composer:

```bash
composer require derafu/container
```

## A Quick Tour

```php
use Derafu\Container\Vault;

$options = new Vault(
    [&#039;host&#039; =&gt; &#039;imap.example.com&#039;],
    [
        &#039;host&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;, &#039;required&#039; =&gt; true],
        &#039;port&#039; =&gt; [&#039;types&#039; =&gt; &#039;int&#039;, &#039;default&#039; =&gt; 993],
    ]
);

$host = $options-&gt;getReader()-&gt;requireString(&#039;host&#039;); // string: &quot;imap.example.com&quot;
$port = $options-&gt;getReader()-&gt;requireInt(&#039;port&#039;);    // int: 993 (the default of the schema).

try {
    $options-&gt;set(&#039;port&#039;, &#039;abc&#039;); // Rejected: the port must be an int.
} catch (\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException $exception) {
    $options-&gt;getReader()-&gt;requireInt(&#039;port&#039;); // Still 993: the failed change did nothing.
}
```

## Container Comparison

| Feature                   | Bag | Vault  | Store | Journal |
|---------------------------|-----|--------|-------|---------|
| Schema                    | No  | Simple | JSON  | No      |
| Validation on every change| No  | Yes    | Yes   | No      |
| Defaults and normalizers  | No  | Yes    | Defaults | No   |
| Nested data               | Yes | Yes    | Yes   | No      |
| Dot notation              | Yes | Yes    | Yes   | No      |
| Sequential                | No  | No     | No    | Yes     |
| Typed reader              | Yes | Yes    | Yes   | Yes     |

## Where to Go Next

- [Containers](containers): `Bag`, `Vault`, `Store` and `Journal` one by one.
- [Typed Readers](typed-getters): read values with the type you expect.
- [Validation](validation): schemas, when they are checked and what happens when they fail.
- [Translations](translations): the exceptions of the package and how to translate them.




---

## Containers

Containers

# Containers

All the containers implement `Derafu\Container\Contract\ContainerInterface`,
which has the methods to read and write by key (with dot notation), plus the
[typed reader](typed-getters):

```php
use Derafu\Array\ArrayReader;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;

interface ContainerInterface extends ArrayAccess, JsonSerializable
{
    public function all(): array;
    public function set(string $key, mixed $value): static;
    public function get(string $key, mixed $default = null): mixed;
    public function has(string $key): bool;
    public function clear(?string $key = null): void;
    public function collection(): ArrayCollection;
    public function matching(Criteria $criteria): ArrayCollection;

    public function getReader(): ArrayReader;
    public function getContainer(string $key, ?array $default = null): ?static;
    public function requireContainer(string $key): static;
}
```

The `ArrayAccess` offsets use the same keys: `$container[&#039;user.name&#039;]` is the
same as `$container-&gt;get(&#039;user.name&#039;)`.

Wherever a container is given data (the constructor of every container, and
`replace()` and `merge()` of `Bag`), the data can be an array, an
`ArrayObject` or another container of any kind. A container is copied with its
data only: the new container does not have the schema of the other one, it is
valid for its own, and a change in one of them does not change the other.

```php
$options = new Vault(
    new Bag([&#039;name&#039; =&gt; &#039;Ada&#039;]),
    [&#039;name&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;], &#039;debug&#039; =&gt; [&#039;types&#039; =&gt; &#039;bool&#039;, &#039;default&#039; =&gt; false]]
);

$options-&gt;all(); // [&#039;debug&#039; =&gt; false, &#039;name&#039; =&gt; &#039;Ada&#039;]
```

## Bag

A flexible container without restrictions. It is the one to use when you only
need a place to keep data.

```php
use Derafu\Container\Bag;

$bag = new Bag();
$bag-&gt;set(&#039;user.name&#039;, &#039;John&#039;);
$bag-&gt;set(&#039;user.email&#039;, &#039;john@example.com&#039;);

echo $bag-&gt;get(&#039;user.name&#039;); // &quot;John&quot;
```

It adds three methods:

```php
$bag-&gt;merge([&#039;user&#039; =&gt; [&#039;age&#039; =&gt; 30]]); // Recursive: keeps user.name and user.email.
$bag-&gt;replace([&#039;other&#039; =&gt; 1]);          // Replaces everything.
$bag-&gt;remove(&#039;other&#039;);                  // Removes a key.
```

## Vault

A container with a simple schema. Each key of the schema says its types, whether
it is required, its accepted values, its default and how to normalize it. The
validation is made by `symfony/options-resolver`.

```php
use Derafu\Container\Vault;

$vault = new Vault(
    [&#039;user&#039; =&gt; [&#039;name&#039; =&gt; &#039;John&#039;]],
    [
        &#039;user&#039; =&gt; [
            &#039;types&#039; =&gt; &#039;array&#039;,
            &#039;required&#039; =&gt; true,
            &#039;schema&#039; =&gt; [
                &#039;name&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;, &#039;required&#039; =&gt; true],
                &#039;age&#039; =&gt; [&#039;types&#039; =&gt; &#039;int&#039;, &#039;default&#039; =&gt; 18],
            ],
        ],
    ]
);

$vault-&gt;get(&#039;user.age&#039;); // 18, the default.
```

The constructor takes the data, the schema and whether the keys that the schema
does not define are allowed (`false` by default). See [Validation](validation)
for every key of the schema and for what happens on each change.

## Store

A container validated with [JSON Schema](https://json-schema.org) (draft 2020-12)
through `opis/json-schema`. Use it when the schema comes from outside, or when
you need what JSON Schema has and the simple schema of `Vault` does not (formats,
`items`, `oneOf`, patterns...).

```php
use Derafu\Container\Store;

$store = new Store(
    [&#039;user&#039; =&gt; [&#039;name&#039; =&gt; &#039;John&#039;, &#039;email&#039; =&gt; &#039;john@example.com&#039;]],
    [
        &#039;properties&#039; =&gt; [
            &#039;user&#039; =&gt; [
                &#039;type&#039; =&gt; &#039;object&#039;,
                &#039;required&#039; =&gt; [&#039;name&#039;, &#039;email&#039;],
                &#039;properties&#039; =&gt; [
                    &#039;name&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
                    &#039;email&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;, &#039;format&#039; =&gt; &#039;email&#039;],
                ],
            ],
        ],
    ]
);
```

`$schema` and `type: object` are added to the schema when you do not give them,
so `getSchema()` returns them. The `default` of a property is applied when the
property has no value.

## Journal

A sequential container: you add items at the end and read them newest first.

```php
use Derafu\Container\Journal;

$journal = new Journal();
$journal-&gt;add([&#039;level&#039; =&gt; &#039;info&#039;, &#039;message&#039; =&gt; &#039;System started&#039;]);
$journal-&gt;add([&#039;level&#039; =&gt; &#039;error&#039;, &#039;message&#039; =&gt; &#039;Connection failed&#039;]);

$errors = array_filter(
    $journal-&gt;reverse(), // Newest first.
    fn (array $entry) =&gt; $entry[&#039;level&#039;] === &#039;error&#039;
);
```

## Reading the Underlying Collection

`collection()` returns the `ArrayCollection` that holds the data, and
`matching()` filters it with a Doctrine `Criteria`:

```php
use Derafu\Container\Bag;
use Doctrine\Common\Collections\Criteria;

$users = new Bag([[&#039;name&#039; =&gt; &#039;Ana&#039;, &#039;age&#039; =&gt; 20], [&#039;name&#039; =&gt; &#039;Bo&#039;, &#039;age&#039; =&gt; 10]]);

$adults = $users-&gt;matching(
    Criteria::create()-&gt;where(Criteria::expr()-&gt;gte(&#039;age&#039;, 18))
);
```

`collection()` is the live collection, not a copy. Changing it directly does not
go through the validation of `Vault` and `Store`; see
[Validation](validation#what-is-not-checked).




---

## Typed Readers

Typed Readers

# Typed Readers

Every container exposes `getReader(): Derafu\Array\ArrayReader`. Typed reads and explicit conversions use [Derafu Array](https://www.derafu.dev/docs/data/array/readers), whose types and conversion rules come from [Derafu Value](https://www.derafu.dev/docs/data/value).

```php
use Derafu\Container\Bag;

$bag = new Bag([&#039;transport&#039; =&gt; [&#039;host&#039; =&gt; &#039;localhost&#039;, &#039;port&#039; =&gt; 993]]);
$reader = $bag-&gt;getReader();

$host = $reader-&gt;requireString(&#039;transport.host&#039;); // &#039;localhost&#039;
$port = $reader-&gt;requireInt(&#039;transport.port&#039;);    // 993
$ssl = $reader-&gt;getBool(&#039;transport.ssl&#039;, true);  // true
```

The typed getters belong to the reader. Container exposes storage, schema validation, Selector operations and creation of child containers.

## Presence and Defaults

Optional reads return the default for missing or null values. Required reads reject both. A present value of the wrong type throws instead of using the default. Valid values such as `0`, `false`, `&#039;&#039;` and `[]` are preserved.

Use `hasKey()` to distinguish a null value from an absent key and `hasValue()` to require a non-null value. Defaults are returned without validation or conversion.

```php
$reader = (new Bag([&#039;retries&#039; =&gt; 0, &#039;note&#039; =&gt; null]))-&gt;getReader();
$reader-&gt;getInt(&#039;retries&#039;, 3); // 0
$reader-&gt;hasKey(&#039;note&#039;);       // true
$reader-&gt;hasValue(&#039;note&#039;);     // false
$reader-&gt;getString(&#039;note&#039;, &#039;none&#039;); // &#039;none&#039;
```

## Validation and Explicit Conversion

Strict getters check existing PHP types. For example, `getFloat()` requires a float; use `getAsFloat()` to convert an integer or numeric text. A conversion returns a value without changing the stored data.

```php
$bag = new Bag([&#039;port&#039; =&gt; &#039;993&#039;, &#039;count&#039; =&gt; 2, &#039;enabled&#039; =&gt; &#039;off&#039;]);
$reader = $bag-&gt;getReader();

$reader-&gt;requireAsInt(&#039;port&#039;);   // 993
$reader-&gt;getAsFloat(&#039;count&#039;);    // 2.0
$reader-&gt;requireAsBool(&#039;enabled&#039;); // false
$bag-&gt;get(&#039;port&#039;);              // &#039;993&#039;: unchanged
```

See [Array Readers](https://www.derafu.dev/docs/data/array/readers) for the complete strict and conversion method pairs, and [Value Casting](https://www.derafu.dev/docs/data/value/casting) for accepted conversions.

## Collections, Enums and Objects

Collection element types are explicit ValueType instances. Arrays preserve arbitrary keys, maps require string keys and lists require consecutive integer keys starting at zero.

```php
use Derafu\Value\ValueType;

$bag = new Bag([&#039;ids&#039; =&gt; [1, 2], &#039;amounts&#039; =&gt; [&#039;12.5&#039;, 2]]);
$reader = $bag-&gt;getReader();

$reader-&gt;requireListOf(&#039;ids&#039;, ValueType::int()); // [1, 2]
$reader-&gt;requireListOf(&#039;ids&#039;, ValueType::toFloat()); // [1.0, 2.0]
$reader-&gt;requireArrayOf(&#039;amounts&#039;, ValueType::toFloat()); // [12.5, 2.0]
```

```php
enum Encryption: string
{
    case Ssl = &#039;ssl&#039;;
    case Tls = &#039;tls&#039;;
}

$mailer = new stdClass();
$reader = (new Bag([&#039;encryption&#039; =&gt; &#039;ssl&#039;, &#039;mailer&#039; =&gt; $mailer]))-&gt;getReader();

$reader-&gt;require(&#039;encryption&#039;, ValueType::backedEnum(Encryption::class)); // Encryption::Ssl
$reader-&gt;require(&#039;mailer&#039;, ValueType::instanceOf(stdClass::class)); // The same object.
```

Generic reads and collection methods preserve their PHPStan generic return types. See [Value Types](https://www.derafu.dev/docs/data/value/types) for nullable types, unions, dates and custom types.

## Navigation and Snapshots

The reader checks for a literal key matching the complete string first, then follows dot notation when that key is absent. Numeric path segments can address array positions. For example, `requireInt(&#039;servers.0.port&#039;)` reads the port of the first server.

Container&#039;s `get()`, `set()`, `has()`, `clear()` and child-container methods retain the full [Selector](https://www.derafu.dev/docs/data/selector) expression language, including bracket indexing. ArrayReader does not interpret those Selector expressions.

A reader is a snapshot of raw stored array data, independent of overrides of Container&#039;s `get()`. Schema defaults and normalizers have already been applied to that data. Obtain a new reader after mutations:

```php
$bag = new Bag([&#039;port&#039; =&gt; 5432]);
$before = $bag-&gt;getReader();
$bag-&gt;set(&#039;port&#039;, 3306);

$before-&gt;requireInt(&#039;port&#039;);           // 5432
$bag-&gt;getReader()-&gt;requireInt(&#039;port&#039;); // 3306
```

Objects inside a snapshot retain their identity; they are not cloned.

## Nested Containers

`getContainer($key, $default = null)` and `requireContainer($key)` belong to Container. They read array data through Selector and create a child of the same container class. A required child rejects missing/null values; an optional child returns null or constructs a child from its supplied array default. Present values of the wrong type throw.

```php
$bag = new Bag([&#039;transports&#039; =&gt; [[&#039;host&#039; =&gt; &#039;localhost&#039;, &#039;port&#039; =&gt; 993]]]);
$transport = $bag-&gt;requireContainer(&#039;transports[0]&#039;);

$transport-&gt;getReader()-&gt;requireString(&#039;host&#039;); // &#039;localhost&#039;
$transport-&gt;set(&#039;port&#039;, 995);
$bag-&gt;get(&#039;transports[0].port&#039;); // 993: changing the child does not write back.
```

A nested reader provides typed access without constructing a mutable container; use `getReader()-&gt;requireReader(&#039;transports.0&#039;)` when that is all you need.

Child containers do not automatically inherit a parent&#039;s schema. Subclasses whose constructor needs additional context override `createChild(array $data, string $key): static`.

## Exceptions

Reader failures follow the [Array exception contract](https://www.derafu.dev/docs/data/array/translations): missing/null required values raise Array MissingValueException and invalid types/conversions raise Array TypeMismatchException. Value type mismatches retain their full path and original cause.

Child-container operations retain `Derafu\Container\Exception\MissingValueException` and `UnexpectedTypeException`. An invalid child value preserves the Value validation exception as its cause. Selector failures retain Selector&#039;s exception contract. See [Translations](translations) for provider registration.

`get()` and ArrayAccess return `mixed`. Use `getReader()` when a typed value is required.




---

## Validation

Validation

# Validation

`Vault` and `Store` have a schema, and they keep their data valid: a change that
breaks the schema is rejected, and the container stays as it was. `Bag` and
`Journal` have no schema and accept everything.

## When the Data Is Checked

| Operation | What is checked |
|---|---|
| The constructor | The data against the schema. |
| `set()` and `$container[&#039;key&#039;] = ...` | The data that would result from the change. |
| `clear()` and `unset($container[&#039;key&#039;])` | The data that would result from the change. |
| `setSchema()` | The stored data against the new schema. |
| `validate()` | The stored data against the current schema. |

The data is also **normalized**: the defaults are applied and, in a `Vault`, the
normalizers run. What is stored after a `set()` is the resolved data, as after
the constructor.

```php
use Derafu\Container\Vault;

$vault = new Vault(
    [&#039;host&#039; =&gt; &#039;imap.example.com&#039;],
    [
        &#039;host&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;, &#039;required&#039; =&gt; true],
        &#039;port&#039; =&gt; [&#039;types&#039; =&gt; &#039;int&#039;, &#039;default&#039; =&gt; 993],
    ]
);

$vault-&gt;set(&#039;port&#039;, &#039;abc&#039;);
// InvalidOptionsException: The option &quot;port&quot; with value &quot;abc&quot; is expected to be
// of type &quot;int&quot;, but is of type &quot;string&quot;.

$vault-&gt;getReader()-&gt;requireInt(&#039;port&#039;); // 993: nothing changed.
```

The change is made on a copy and the container takes it only if it is valid, so
there is nothing to undo and nothing is silenced: the exception always reaches
the caller.

### Removing Keys

`clear()` is checked like any other change. Removing a key with a default gives
it back its default; removing a required key is rejected:

```php
$vault-&gt;clear(&#039;port&#039;);  // Fine: port is 993 again.
$vault-&gt;clear(&#039;host&#039;);  // MissingOptionsException: The required option &quot;host&quot; is missing.
$vault-&gt;clear();        // The same: an empty container does not satisfy the schema.
```

### Changing the Schema

`setSchema()` checks (and normalizes) the data that the container already has.
If it does not comply, neither the schema nor the data change.

```php
$vault = new Vault([&#039;host&#039; =&gt; &#039;a.example.com&#039;]);   // No schema: anything goes.

$vault-&gt;setSchema([
    &#039;host&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;, &#039;required&#039; =&gt; true],
    &#039;port&#039; =&gt; [&#039;types&#039; =&gt; &#039;int&#039;, &#039;default&#039; =&gt; 993],
]);

$vault-&gt;getReader()-&gt;requireInt(&#039;port&#039;); // 993: the default was applied to the stored data.
```

## The Schema of a Vault

The schema is an array: each key is a field, and its value says how the field is
validated. The keys of the field are:

| Key | Meaning |
|---|---|
| `types` | A type, or an array of types, that the value can have: `string`, `int`, `float`, `bool`, `array`, `null`, `object`, a class name... (the types of `OptionsResolver`). |
| `required` | `true` when the field has to be present. |
| `choices` | The values that are accepted. |
| `default` | The value of the field when it is not given. |
| `normalizer` | A closure `fn (Options $options, mixed $value): mixed` that converts the value after it is validated. |
| `schema` | The schema of the fields inside an array field. It nests as deep as needed. |

```php
$vault = new Vault(
    [&#039;price&#039; =&gt; &#039;12.50&#039;, &#039;status&#039; =&gt; &#039;active&#039;, &#039;user&#039; =&gt; [&#039;name&#039; =&gt; &#039;Ada&#039;]],
    [
        &#039;price&#039; =&gt; [
            &#039;types&#039; =&gt; [&#039;string&#039;, &#039;float&#039;],
            &#039;required&#039; =&gt; true,
            &#039;normalizer&#039; =&gt; fn ($options, $value) =&gt; (float) $value,
        ],
        &#039;status&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;, &#039;choices&#039; =&gt; [&#039;active&#039;, &#039;inactive&#039;]],
        &#039;user&#039; =&gt; [
            &#039;types&#039; =&gt; &#039;array&#039;,
            &#039;schema&#039; =&gt; [
                &#039;name&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;, &#039;required&#039; =&gt; true],
                &#039;age&#039; =&gt; [&#039;types&#039; =&gt; &#039;int&#039;, &#039;default&#039; =&gt; 18],
            ],
        ],
    ]
);

$vault-&gt;getReader()-&gt;requireFloat(&#039;price&#039;);   // 12.5
$vault-&gt;getReader()-&gt;requireInt(&#039;user.age&#039;);  // 18
$vault-&gt;set(&#039;status&#039;, &#039;other&#039;);  // Rejected: not one of the choices.
```

A field whose configuration is not valid (a `types` that is not a string or an
array of strings, a `schema` that is not an array, a `normalizer` that is not a
closure, a field that is not an array...) throws
`TranslatableInvalidArgumentException` when the schema is used.

### Keys the Schema Does Not Define

By default a key that is not in the schema is rejected:

```php
$vault-&gt;set(&#039;endpoint&#039;, &#039;x&#039;);
// UndefinedOptionsException: The option &quot;endpoint&quot; does not exist.
```

The policy can be changed in three places, from the most general to the most
specific:

1. The constructor: `new Vault($data, $schema, allowUndefinedKeys: true)`. The
   `Vault` keeps it and uses it in `set()`, `clear()`, `setSchema()` and
   `validate()`.
2. The key `__allowUndefinedKeys` in a schema (`true` or `false`), which
   overrides the constructor for that level.
3. `validate(true)` or `validate(false)`, only for that call.

A nested schema inherits the policy of the level above and can override it with
its own `__allowUndefinedKeys`:

```php
$vault = new Vault($data, [
    &#039;__allowUndefinedKeys&#039; =&gt; true,                 // The root accepts more keys...
    &#039;user&#039; =&gt; [
        &#039;schema&#039; =&gt; [
            &#039;__allowUndefinedKeys&#039; =&gt; false,        // ...but `user` does not.
            &#039;name&#039; =&gt; [&#039;types&#039; =&gt; &#039;string&#039;],
        ],
    ],
]);
```

### The Exceptions of a Vault

The errors of the data are the exceptions of `symfony/options-resolver`
(`InvalidOptionsException`, `MissingOptionsException`,
`UndefinedOptionsException`), which extend `InvalidArgumentException`. They are
not translated. The errors of the schema itself are
`TranslatableInvalidArgumentException`.

## The Schema of a Store

A `Store` is validated with JSON Schema (draft 2020-12). You can give the schema
as an array; `$schema` and `type: object` are added if they are missing.

```php
use Derafu\Container\Store;

$store = new Store(
    [&#039;name&#039; =&gt; &#039;Ada&#039;],
    [
        &#039;required&#039; =&gt; [&#039;name&#039;],
        &#039;properties&#039; =&gt; [
            &#039;name&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;],
            &#039;lang&#039; =&gt; [&#039;type&#039; =&gt; &#039;string&#039;, &#039;default&#039; =&gt; &#039;es&#039;],
        ],
    ]
);

$store-&gt;get(&#039;lang&#039;);                 // &quot;es&quot;: the default of the property.
$store-&gt;set(&#039;name&#039;, 5);              // Rejected.
$store-&gt;clear(&#039;name&#039;);               // Rejected: `name` is required.
```

The errors are `TranslatableInvalidArgumentException`, with every problem found
and where it is:

```text
Failed to validate the data against the JSON schema. The data (integer) must
match the type: string in /name.
```

JSON Schema defaults are applied to the data, but the data must be an object at
its root: an empty container is validated as `{}`.

## What Is Not Checked

The validation guards the methods of the container. These ways in do not go
through it:

- `collection()` returns the live `ArrayCollection`. Changing it changes the
  container without validating. It is a deliberate way for the code that needs
  to work with the collection directly.
- An object stored in the container can be changed by whoever holds it.

`validate()` checks the stored data again, for when you used one of those:

```php
$vault-&gt;collection()-&gt;set(&#039;port&#039;, &#039;abc&#039;);   // Not checked.
$vault-&gt;validate();                         // InvalidOptionsException.
```

`validate()` does not change the data. In a `Vault` it takes an optional
argument to override the policy of undefined keys for that call.




---

## Translations

Translations

# Translations

The exceptions of `derafu/container` can be translated. This page explains what
is translatable, what ships out of the box and how to activate it in your
application.

## What&#039;s Translatable

Every exception the package throws is translatable (see
[`derafu/translation`](https://www.derafu.dev/docs/core/translation)):

- `MissingValueException` and `UnexpectedTypeException`, from child-container creation through `getContainer()` / `requireContainer()`.
- The errors of a `Store` (data that does not comply with the JSON schema, data
  or schema that can not be converted to JSON).
- The errors of the schema of a `Vault`.
- A value that can not be used as the key of a container.

The errors of the data of a `Vault` are the exceptions of
`symfony/options-resolver`, which are not translatable.

Messages are written in ICU MessageFormat, with the English text as the
translation id and named placeholders:

```php
use Derafu\Container\Bag;

try {
    (new Bag([&#039;transport&#039; =&gt; &#039;abc&#039;]))-&gt;requireContainer(&#039;transport&#039;);
} catch (\Throwable $e) {
    $exception = $e;
    echo $e-&gt;getMessage();
    // &quot;The value of transport must be of type array; string given.&quot;
}
```

Without a translator configured, `getMessage()` already returns the formatted
English text, so the package works as before whether or not you set up
translation.

## Reader and Selector Errors

Reads performed through `getReader()` execute in Derafu Array and use its translatable exceptions. Register Array&#039;s resource provider to translate those messages; see [Array Translations](https://www.derafu.dev/docs/data/array/translations). Direct Value operations use Value&#039;s provider, described in [Value Translations](https://www.derafu.dev/docs/data/value/translations).

Container retains its own exception classes for child creation. If the selected child value is not an array, UnexpectedTypeException preserves the Value mismatch as its previous exception. The outer Container message remains translated with Container&#039;s provider. Selector failures remain Selector exceptions.

## What Ships

- `resources/translations/errors+intl-icu.es.php`: a Spanish translation for
  every message of the package.
- `Derafu\Container\Translation\ContainerTranslationResourceProvider`: a
  `TranslationResourceProviderInterface` pointing at that directory.
- `resources/config/container-services.yaml`: a recipe for applications that use
  `symfony/dependency-injection`.

None of them does anything by itself: `derafu/container` is a library, it does
not build a `Translator`.

## Activating It (Plain PHP)

```php
use Derafu\Container\Translation\ContainerTranslationResourceProvider;
use Derafu\Translation\TranslatorFactory;

$translator = TranslatorFactory::create(
    defaultLocale: &#039;es&#039;,
    fallbackLocales: [&#039;es&#039;, &#039;en&#039;],
    resourceProviders: [new ContainerTranslationResourceProvider()],
);

echo $exception-&gt;trans($translator);
// &quot;El valor de transport debe ser de tipo array; se recibió string.&quot;
```

## Activating It (Dependency Injection)

```yaml
imports:
    - { resource: &#039;../vendor/derafu/translation/resources/config/translation-services.yaml&#039; }
    - { resource: &#039;../vendor/derafu/container/resources/config/container-services.yaml&#039; }

services:
    Symfony\Component\Translation\Translator:
        factory: [&#039;Derafu\Translation\TranslatorFactory&#039;, &#039;create&#039;]
        arguments:
            $defaultLocale: &#039;es&#039;
            $fallbackLocales: [&#039;es&#039;, &#039;en&#039;]
            $resourceProviders: !tagged_iterator derafu_translation.resource_provider
```

`container-services.yaml` tags `ContainerTranslationResourceProvider` with
`derafu_translation.resource_provider`, so it is picked up automatically.





---
Last updated on 15/11/2026
#php
