7. Factory

7.1. Create a Custom Factory class for your resource

<?php

/*
 * This file is part of the Openjet package.
 *
 * (c) Openjet SA
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Openjet\Component\Customer\Factory;

use Openjet\Component\Customer\CustomerPrototypes;
use Openjet\Component\Customer\Model\CustomerInterface;
use Openjet\Component\Resource\Factory\Factory as BaseFactory;
use Openjet\Component\Resource\Repository\RepositoryInterface;

class CustomerFactory extends BaseFactory implements CustomerFactoryInterface
{
    /**
     * @var RepositoryInterface
     */
    protected $businessUnitRepository;

    /**
     * @param string              $className
     * @param RepositoryInterface $businessUnitRepository
     */
    public function __construct($className, RepositoryInterface $businessUnitRepository)
    {
        parent::__construct($className);
        $this->businessUnitRepository = $businessUnitRepository;
    }

    /**
     * @return CustomerInterface
     */
    public function createNew()
    {
        return parent::createNew()
            ->setBusinessUnit($this->businessUnitRepository->findOneBy(['default' => true]));
    }

    /**
     * {@inheritdoc}
     */
    public function createNewAccount()
    {
        return $this->createNew()->setPrototype(CustomerPrototypes::ACCOUNT);
    }
}

7.2. Register the Factory as a service

Warning

the registration of a factory is only needed when it has some custom constructor dependencies.

<parameters>
    <parameter key="openjet.factory.customer.class">Openjet\Component\Customer\Factory\CustomerFactory</parameter>
</parameters>

<services>
    <service id="openjet.factory.customer" class="%openjet.factory.customer.class%">
        <argument>%openjet.model.customer.class%</argument>
        <argument type="service" id="openjet.repository.business_unit"/>
        <argument type="service" id="openjet.repository.customer_category"/>
    </service>
</services>

7.3. Configure the factory for your resource

openjet_resource:
    resources:
        customer:
            classes:
                factory: Openjet\Component\Customer\Factory\CustomerFactory

7.4. Use the new method of the factory in routing

openjet_customer_account_create:
    path: /customers/account/new
    methods: [GET, POST]
    defaults:
        _controller: openjet.controller.customer:createAction
        _sylius:
            factory: createNewAccount

7.5. What happens while overriding Factories?

  • The parameter openjet.factory.customer.class contains Openjet\Component\Customer\Factory\CustomerFactory.
  • The factory service openjet.factory.customer is using your new class.
  • Under the openjet.factory.customer service you have got all methods from the base factory available and all you have added.