Skip to content

Implementing your own stock storage

Implementing your own stock storage

Overview

Shopware stores stock as simple integer values in the product table. If you need a more advanced stock management system or would like to write the stock alterations to a different system, you can implement your own stock storage.

Prerequisites

Here you will be decorating a service; therefore, it will be helpful to familiarise yourself with the Adjusting a Service guide.

Add a decorator to load the stock

First, to communicate stock alterations to a third-party service, you will have to decorate \Shopware\Core\Content\Product\Stock\AbstractStockStorage and implement the alter method. This method is triggered with an array of StockAlteration's, which contains:

  • the Product and Line Item IDs,
  • the old quantity and
  • the new quantity.

The alter method will be called when the stock of a product should be updated. The $changes array contains a list of StockAlteration instances. These objects contain the following properties/methods:

Property/MethodTypeDescription
lineItemIdstringThe ID of the line item that triggered the stock update
productIdstringThe ID of the product that should be updated
quantityBeforeintThe old product stock level
newQuantityintThe new product stock level
quantityDelta()intThe difference between the old and new stock level

Stock changing scenarios

The following list contains all the scenarios that trigger stock alterations. All implementations of AbstractStockStorage should be able to handle these scenarios.

  • Order placed
  • Order canceled
  • Order deleted
  • Cancelled order, reopened
  • Line item added to the order
  • Line item removed from an order
  • Line item updated (Product qty increased)
  • Line item updated (Product qty decreased)
  • Line item updated (Product sku changed)

All of these scenarios are handled by the event subscriber Shopware\Core\Content\Product\Stock\OrderStockSubscriber.

Further extension points for advanced customization

  1. If you need to listen to more events to trigger stock alterations, you can create an event subscriber for the required events and call the \Shopware\Core\Content\Product\Stock\AbstractStockStorage::alter method with a StockAlteration instance representative of the alteration.
  2. If you don't want to use Shopware's default events and stock storage, you can implement your own system and recommend that the project owner disables the Shopware stock management system. Refer them to Configuration guide.