For the complete documentation index, see llms.txt. This page is also available as Markdown.

Resource factories

Resource factories are used on Create operations to instantiate your resource.

Default factory for your resource

By default, a resource factory is defined to your resource Sylius\Component\Resource\Factory\Factory.

It has a createNew method with no arguments.

Inject the factory in your service

If you are using Symfony autowiring, you can inject the resource factory using the right variable name.

src/MyService.php
namespace App;

use Sylius\Resource\Factory\FactoryInterface;

final class MyService
{
    public function __construct(
        private FactoryInterface $bookFactory,
    ) {}
}

In this example, the app.factory.book will be injected in your $bookFactory

You can find the variable name using this debug command:

Define your custom factory

Configure your factory

Use your custom method

Use it on your create operation

Pass arguments to your method

You can pass arguments to your factory method.

3 variables are available:

  • request: to retrieve data from the request via Symfony\Component\HttpFoundation\Request

  • token: to retrieve data from the authentication token via Symfony\Component\Security\Core\Authentication\Token\TokenInterface

  • user: to retrieve data from the logged-in user via Symfony\Component\Security\Core\User\UserInterface

It uses the Symfony expression language component.

Use it on your create operation

Use a factory without declaring it

You can use a factory without declaring it on services.yaml.

Use a callable for your custom factory

Last updated

Was this helpful?