Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 30 ยท Projects

Project: A Custom Wishlist API

Build a wishlist for logged-in customers: a custom entity, a migration, a Store API route with validation and a JSON response, plus tests and runnable stand-ins.

A wishlist is the classic first "real" Shopware extension. It needs a table of its own, an endpoint that a storefront or a mobile app can call, and one rule that is easy to forget: every row belongs to exactly one customer, and a customer must never see another customer's list. In this project you put the earlier lessons together: a custom entity, a migration, repositories and a Store API route.

Shopware cannot run on this site, so the real plugin code below is read-only. After each part there is a plain-PHP stand-in you can run: a SQLite repository and a tiny request handler. They show the logic (uniqueness, ownership, validation, status codes), not the framework's classes. The text always says which is which.

What we are building

The plugin is called AcmeWishlist. It offers three Store API endpoints for a logged-in customer:

Method and path What it does
GET /store-api/acme/wishlist Lists the customer's saved product ids
POST /store-api/acme/wishlist Adds a product (body: productId)
DELETE /store-api/acme/wishlist/{productId} Removes a product
flowchart LR
    C["Client<br/>(storefront or app)"] --> R["Route<br/>_loginRequired"]
    R --> V["Validate input"]
    V --> Q["Repository<br/>acme_wishlist_item"]
    Q --> T[("Table")]
    R --> J["JSON response"]

A request passes the login check, validation and the repository before a response is built.

Two design decisions keep the project small and safe. First, the route never accepts a customer id from the client: it reads the customer from the sales channel context, which Shopware fills from the context token. Second, adding the same product twice is not an error. It is a no-op, so a client that retries after a network failure does the right thing (see Idempotency).

Step 1: the entity and the migration

The definition has an id, the customer, the product and the usual timestamps. Product references need the product's version id as well, because products are versioned entities.

PHP
<?php declare(strict_types=1);

namespace Acme\Wishlist\Core\Content\WishlistItem;

use Shopware\Core\Checkout\Customer\CustomerDefinition;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Field\FkField;
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\ManyToOneAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\Field\ReferenceVersionField;
use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;

class WishlistItemDefinition extends EntityDefinition
{
    public const ENTITY_NAME = 'acme_wishlist_item';

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

    protected function defineFields(): FieldCollection
    {
        return new FieldCollection([
            (new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),
            (new FkField('customer_id', 'customerId', CustomerDefinition::class))->addFlags(new Required()),
            (new FkField('product_id', 'productId', ProductDefinition::class))->addFlags(new Required()),
            (new ReferenceVersionField(ProductDefinition::class))->addFlags(new Required()),
            new ManyToOneAssociationField('product', 'product_id', ProductDefinition::class, 'id', false),
        ]);
    }
}

The collection and entity classes follow the pattern from Custom Entities and Definitions; they are omitted here. The migration creates the table and, importantly, a unique key over customer and product, so the database itself refuses duplicates even if two requests race.

PHP
<?php declare(strict_types=1);

namespace Acme\Wishlist\Migration;

use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Migration\MigrationStep;

class Migration1730000000CreateWishlistItem extends MigrationStep
{
    public function getCreationTimestamp(): int
    {
        return 1730000000;
    }

    public function update(Connection $connection): void
    {
        $connection->executeStatement('
            CREATE TABLE IF NOT EXISTS `acme_wishlist_item` (
                `id` BINARY(16) NOT NULL,
                `customer_id` BINARY(16) NOT NULL,
                `product_id` BINARY(16) NOT NULL,
                `product_version_id` BINARY(16) NOT NULL,
                `created_at` DATETIME(3) NOT NULL,
                `updated_at` DATETIME(3) NULL,
                PRIMARY KEY (`id`),
                UNIQUE KEY `uniq.acme_wishlist_item.customer_product` (`customer_id`, `product_id`),
                CONSTRAINT `fk.acme_wishlist_item.customer_id` FOREIGN KEY (`customer_id`)
                    REFERENCES `customer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        ');
    }

    public function updateDestructive(Connection $connection): void
    {
    }
}

ON DELETE CASCADE on the customer matters for privacy: when a customer is deleted, their wishlist rows disappear with them (more in Privacy and Compliance). A real product foreign key must cover both product_id and product_version_id, which makes the SQL longer; a plugin test against a real database is the place to check that constraint.

Try it: the repository stand-in

This stand-in is a SQLite table with the same unique key. The id is derived from customer and product, the way you would make an upsert idempotent in the DAL. Real Shopware uses UUIDs in binary columns and the EntityRepository; here it is a hash and PDO.

PHP A wishlist repository with a unique key

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.

The third add returns false because the unique key already holds that pair, and the first customer's list never contains anything the second customer added.

Step 2: the Store API route

Following the pattern from Custom Store API Routes, the route has an abstract base class so other plugins can decorate it, a concrete class and a response class. The concrete class carries the routing attributes.

PHP
<?php declare(strict_types=1);

namespace Acme\Wishlist\Core\Content\WishlistItem\SalesChannel;

use Shopware\Core\Framework\Plugin\Exception\DecorationPatternException;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route(defaults: ['_routeScope' => ['store-api']])]
class WishlistRoute extends AbstractWishlistRoute
{
    public function __construct(private readonly WishlistService $wishlist)
    {
    }

    public function getDecorated(): AbstractWishlistRoute
    {
        throw new DecorationPatternException(self::class);
    }

    #[Route(
        path: '/store-api/acme/wishlist',
        name: 'store-api.acme.wishlist.load',
        methods: ['GET'],
        defaults: ['_loginRequired' => true],
    )]
    public function load(SalesChannelContext $context): WishlistResponse
    {
        $customer = $context->getCustomer(); // never null: _loginRequired guarantees it

        return new WishlistResponse($this->wishlist->productIds($customer->getId(), $context->getContext()));
    }

    #[Route(
        path: '/store-api/acme/wishlist',
        name: 'store-api.acme.wishlist.add',
        methods: ['POST'],
        defaults: ['_loginRequired' => true],
    )]
    public function add(Request $request, SalesChannelContext $context): WishlistResponse
    {
        $productId = (string) $request->request->get('productId');
        $this->wishlist->add($context->getCustomer()->getId(), $productId, $context);

        return new WishlistResponse($this->wishlist->productIds($context->getCustomer()->getId(), $context->getContext()));
    }
}

The details that deserve attention:

  • _loginRequired makes Shopware reject anonymous requests before your method runs. The customer id comes from the context, never from the request body.
  • The response class extends StoreApiResponse and wraps a Struct. The JSON the client receives carries an apiAlias field that names the struct type, which clients can use to tell response kinds apart.
  • Routes of a plugin must be imported (through the plugin's routes.xml) and the route service must be public, as described in the lesson on routes. Clear the cache after adding either.

Validation

Do not trust productId. Shopware's DataValidator and DataValidationDefinition check input against Symfony constraints and throw a ConstraintViolationException, which the framework turns into a 400 response with one error per field, each pointing at the field.

PHP
$definition = new DataValidationDefinition('acme.wishlist.add');
$definition->add('productId', new NotBlank(), new Uuid());

$this->validator->validate(['productId' => $productId], $definition);

Then check that the product exists and is visible in this sales channel. The Uuid constraint only says the string has the right shape. A search by id with the context's sales channel filter answers the second question. Without it, a client could store ids of products it was never allowed to see.

Try it: a request handler stand-in

This stand-in plays the part of the router plus the route methods. It checks the login, validates the id with a regular expression, calls the repository, and returns a [status, body] pair. The error format is simplified; the real framework builds it for you.

PHP Routes, validation and ownership

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.

Notice the second POST for the same product still answers 200 with an unchanged list, ben sees an empty list although anna has saved products, and the two failure kinds (bad shape and unknown product) get different status codes and a pointer to the field.

Step 3: tests

Two kinds of tests pay for themselves. A unit test covers pure logic, such as "which ids are valid" or the mapping from entities to the response. An integration test uses the real container and database through Shopware's test behavior traits, which is where the migration, the definition and the unique key are proven to agree. This is a sketch, not a complete test:

PHP
<?php declare(strict_types=1);

namespace Acme\Wishlist\Test;

use PHPUnit\Framework\TestCase;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour;

class WishlistRepositoryTest extends TestCase
{
    use IntegrationTestBehaviour;

    public function testSameProductIsStoredOnce(): void
    {
        /** @var EntityRepository $repository */
        $repository = static::getContainer()->get('acme_wishlist_item.repository');
        $context = Context::createDefaultContext();

        // create a customer and a product first (helpers or factories), then:
        $row = ['id' => $id, 'customerId' => $customerId, 'productId' => $productId];
        $repository->upsert([$row], $context);
        $repository->upsert([$row], $context);

        static::assertSame(1, $repository->search(new Criteria(), $context)->getTotal());
    }
}

Test the failure modes too: an anonymous request, an invalid id, and a product from a different sales channel. The details of the helpers differ between Shopware versions, so check the test base classes of the version you target; Testing Plugins covers the setup.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the wishlist route read the customer id from?

    The context is filled by Shopware from the context token and the login state. A client-supplied id would let one customer read another's list.
  2. 2. What makes adding the same product twice harmless?

    The database enforces uniqueness even when two requests race, and the write treats the existing row as success. A retry then gives the same end state.
  3. 3. Why does the Uuid constraint alone not make the productId safe?

    Shape validation and existence checks are separate. Look the product up with the sales channel context before storing it.
  4. 4. What does ON DELETE CASCADE on the customer foreign key give you?

    Personal data should not outlive the person. The cascade removes the rows together with the customer, with no extra cleanup code.

Summary

  • The project combines a definition, a migration, a repository-backed service and a Store API route.
  • Read the customer from the sales channel context and mark routes with _loginRequired; never accept an owner id from the client.
  • A unique key plus a conflict-tolerant write makes "add" idempotent and race-safe.
  • Validate shape with DataValidator, then check existence and visibility with a search.
  • Unit-test pure logic and integration-test the real container and database; the stand-ins here show the logic, not the framework.

Next, build a background job in Project: Order Export Task.