Customer and ShopUser¶

For handling customers of your system Sylius is using a combination of two entities - Customer and ShopUser. The difference between these two entities is simple: the Customer is a guest in your shop and the ShopUser is a user registered in the system - they have an account.

Customer¶

The Customer entity was created to collect data about non-registered guests of the system - ones that has been buying without having an account or that have somehow provided us their e-mail.

How to create a Customer programmatically?¶

As usual, use a factory. The only required field for the Customer entity is email, provide it before adding it to the repository.

/** @var CustomerInterface $customer */
$customer = $this->container->get('sylius.factory.customer')->createNew();

$customer->setEmail('[email protected]');

$this->container->get('sylius.repository.customer')->add($customer);

The Customer entity can of course hold other information besides an email, it can be for instance firstName, lastName or birthday.

Note

The relation between the Customer and ShopUser is bidirectional. Both entities hold a reference to each other.

ShopUser¶

ShopUser entity is designed for customers that have registered in the system - they have an account with both e-mail and password. They can visit and modify their account.

While creating new account the existence of the provided email in the system is checked - if the email was present - it will already have a Customer therefore the existing one will be assigned to the newly created ShopUser, if not - a new Customer will be created together with the ShopUser.

Note

Please note that if a newly created ShopUser has been assigned to an existing Customer, they will have access to previously placed orders as a guest.

How to create a ShopUser programmatically?¶

Assuming that you have a Customer (either retrieved from the repository or a newly created one) - use a factory to create a new ShopUser, assign the existing Customer and a password via the setPlainPassword() method.

/** @var ShopUserInterface $user */
$user = $this->container->get('sylius.factory.shop_user')->createNew();

// Now let's find a Customer by their e-mail:
/** @var CustomerInterface $customer */
$customer = $this->container->get('sylius.repository.customer')->findOneBy(['email' => '[email protected]']);

// and assign it to the ShopUser
$user->setCustomer($customer);
$user->setPlainPassword('pswd');

$this->container->get('sylius.repository.shop_user')->add($user);

Changing the ShopUser password¶

The already set password of a ShopUser can be easily changed via the setPlainPassword() method.

$user->getPassword(); // returns encrypted password - 'pswd'

$user->setPlainPassword('resu1');
// the password will now be 'resu1' and will become encrypted while saving the user in the database