Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 30 ยท Data Abstraction Layer

Custom Entities and Definitions

Learn how the Shopware Data Abstraction Layer describes data with EntityDefinition, field flags, Entity and EntityCollection classes, and the services.xml tag.

Almost every Shopware plugin needs to store something: a wishlist, a badge, an export log, a supplier list. Shopware does not ask you to write SQL for each of those or to map tables with Doctrine annotations. Instead it has its own layer, the Data Abstraction Layer (DAL). You describe an entity once, in PHP, and the DAL gives you a repository, an HTTP API, validation, translations, versioning and search for that description.

This lesson covers the first half of that story: how an entity is described. You will meet the EntityDefinition class, field types and flags, the Entity and EntityCollection classes, and the services.xml tag that makes the DAL notice your definition. The table itself comes from a database migration, and reading and writing are covered in Reading and Writing with Repositories. Shopware cannot run on this site, so the real classes are read-only here, and the runnable examples are plain PHP stand-ins that follow the same idea.

Why the DAL exists

Doctrine is part of the Symfony ecosystem (see Doctrine Setup), and Shopware uses its DBAL connection for raw queries. But the platform needs more than an ORM gives. Every entity must be reachable through the Admin API with the same filter syntax. Translations, inheritance between product variants, versioning and write protection must work identically for core entities and plugin entities. A single definition class is the one source from which all of that is derived.

In practice this means:

  • The definition is a description: entity name, fields, flags, associations.
  • The table is created by you, in a migration. The DAL does not generate it.
  • The repository is created for you from the definition and is registered in the container.
  • The Entity and EntityCollection classes are plain value objects that hold the hydrated rows.
flowchart LR
    D["EntityDefinition<br/>(fields + flags)"] --> R["Repository<br/>acme_vendor.repository"]
    D --> A["Admin API<br/>/api/acme-vendor"]
    D --> V["Validation +<br/>write protection"]
    M["Migration<br/>(creates the table)"] --> T[("MySQL table<br/>acme_vendor")]
    R --> T

One definition feeds the repository, the API and validation. The migration stays separate and creates the real table.

Writing an EntityDefinition

A definition extends Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition. It has to answer a few questions: what is the entity called, which fields does it have, and which classes represent one row and a list of rows.

PHP
<?php declare(strict_types=1);

namespace Acme\Vendors\Core\Content\Vendor;

use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Field\BoolField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\PrimaryKey;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\Required;
use Shopware\Core\Framework\DataAbstractionLayer\Field\IdField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\IntField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\StringField;
use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;

class VendorDefinition extends EntityDefinition
{
    public const ENTITY_NAME = 'acme_vendor';

    public function getEntityName(): string
    {
        return self::ENTITY_NAME;
    }

    public function getCollectionClass(): string
    {
        return VendorCollection::class;
    }

    public function getEntityClass(): string
    {
        return VendorEntity::class;
    }

    protected function defineFields(): FieldCollection
    {
        return new FieldCollection([
            (new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),
            (new StringField('name', 'name'))->addFlags(new Required()),
            new StringField('website', 'website'),
            new IntField('rating', 'rating'),
            new BoolField('active', 'active'),
        ]);
    }
}

Every field takes two names: the property name (name, camelCase, used in PHP and in the API) and the storage name (the column, snake_case, such as created_at). For a one-word name they are equal. The entity name should start with your vendor prefix so it can never collide with a core table, and by convention it equals the table name.

Field types

The Field namespace holds one class per kind of data. These are the ones you will use most:

Field class Stores
IdField A UUID, kept as BINARY(16) in MySQL and hex in PHP
StringField A short string, with a maximum length
LongTextField Long text
IntField, FloatField Numbers
BoolField A boolean
DateTimeField A timestamp
JsonField A JSON structure
FkField A foreign key to another entity's id
ManyToOneAssociationField and friends Relations between entities

The base class also adds createdAt and updatedAt fields for you, so your migration should create created_at and updated_at columns. A mismatch between definition and table is the most common reason for a new entity to fail on its first write.

Flags

A field's behavior is tuned with flags, added through addFlags(). Two matter immediately:

  • PrimaryKey marks the field as part of the key. Almost every definition has an IdField with this flag.
  • Required tells the DAL that a write must supply a value. If you leave it out, the write fails validation before it reaches the database.

Other flags worth knowing by name are ApiAware (expose the field through the Store API), Inherited (read a variant's value from its parent), SearchRanking (include the field in text search) and WriteProtected. Flags are metadata: the same field can be written one way by the Admin API and read another way by the Store API.

The Entity and the EntityCollection

Rows come back as objects. An entity class extends Shopware\Core\Framework\DataAbstractionLayer\Entity, uses the EntityIdTrait, and has one property per field with a getter and setter:

PHP
<?php declare(strict_types=1);

namespace Acme\Vendors\Core\Content\Vendor;

use Shopware\Core\Framework\DataAbstractionLayer\Entity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityIdTrait;

class VendorEntity extends Entity
{
    use EntityIdTrait;

    protected string $name;

    protected ?string $website = null;

    protected ?int $rating = null;

    protected bool $active = false;

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    // getWebsite(), getRating(), isActive() and the setters follow the same pattern
}

Properties must be protected (not private), because the DAL hydrates them from a parent context. The property name must match the field's property name exactly.

The collection class wraps a list of entities and enforces their type:

PHP
<?php declare(strict_types=1);

namespace Acme\Vendors\Core\Content\Vendor;

use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;

/**
 * @extends EntityCollection<VendorEntity>
 */
class VendorCollection extends EntityCollection
{
    protected function getExpectedClass(): string
    {
        return VendorEntity::class;
    }
}

The collection offers helpers like first(), get($id), getIds() and filter(). Because every result of a repository search is such a collection, you get a typed list rather than an array of arrays.

Registering the definition

The definition is picked up through a tag in your plugin's Resources/config/services.xml. Without the tag the DAL does not know the entity exists, and no repository is created.

XML
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
           http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="Acme\Vendors\Core\Content\Vendor\VendorDefinition">
            <tag name="shopware.entity.definition" entity="acme_vendor"/>
        </service>
    </services>
</container>

The entity attribute repeats the entity name. After you clear the cache, a service called acme_vendor.repository exists. How tags and the container work is covered in Services and the Dependency Injection Container and, on the Symfony side, Service Tags.

Try it: a definition-driven table

The real DAL has far more machinery, but the key idea is small: a list of field objects, each with flags, is enough to derive a table and to validate a write. This stand-in uses SQLite instead of MySQL and a plain string instead of a 16-byte id, and it generates the table from the definition, which real Shopware does not do (there you write the migration by hand).

PHP A definition that describes a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Next we use the same definition to validate writes and to hydrate rows into entity and collection objects. The Required check mirrors what the DAL does before any SQL runs, and the typed collection mirrors getExpectedClass().

PHP Validating writes and hydrating a typed collection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

What is real here: field objects with flags, the idea that a definition drives both validation and hydration, and a collection that refuses the wrong class. What is stand-in: the SQL, the error text format, and the fact that this repository takes fields directly instead of a definition registered in a container.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the DAL create automatically from an EntityDefinition?

    The definition feeds the repository, the Admin API and validation. The table is not generated; you create it in a migration.
  2. 2. What does the Required flag do?

    Required is checked by the DAL before the write reaches the database. PrimaryKey is a separate flag, and most id fields carry both.
  3. 3. How does the DAL find your definition?

    The tag registers the definition. After a cache clear, the repository service named after the entity exists.
  4. 4. Why must entity properties be protected, not private?

    The DAL fills the properties from outside your class body. The property name also has to match the field's property name.

Summary

  • The DAL describes data once, in an EntityDefinition, and derives the repository, API and validation from it.
  • Fields carry a property name and a storage name; flags such as PrimaryKey and Required tune their behavior.
  • Rows are hydrated into Entity subclasses and listed in a typed EntityCollection.
  • The definition is registered with the shopware.entity.definition tag in services.xml.
  • The table is not generated: create it in a migration and keep it in step with the definition.

Next, create the table for the entity in Database Migrations.