Loading Stock Information from a Different Source
Overview
If Shopware is not the source of truth for your stock data, you can customize the stock loading process and provide your data from a third-party source.
Prerequisites
Here again, 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
For example, to load stock from a third-party API, you need to decorate \Shopware\Core\Content\Product\Stock\AbstractStockStorage
and implement the load
method. When products are loaded in Shopware the load
method will be invoked with the loaded product IDs.
In your load
method, you can access the product IDs from the StockLoadRequest
instance and perform a request to your system to retrieve the data.
You then construct and return a StockDataCollection
full of StockData
instances. Each StockData
instance represents a product.
You can use the static method Shopware\Core\Content\Product\Stock::fromArray()
to construct an instance, passing in an array of the stock attributes.
There are several required values and some optional values.
Attribute | Type | Description | Optional/Required |
---|---|---|---|
productId | string | The product ID | Required |
stock | int | The stock amount | Required |
available | boolean | Whether the product is considered available | Required |
minPurchase | int | The minimum purchase value for this product | Optional |
maxPurchase | int | The maximum purchase value for this product | Optional |
isCloseout | boolean | Whether the product can be ordered if there is not enough stock | Optional |
For example:
$stockData = \Shopware\Core\Content\Product\Stock\StockData::fromArray([
'productId' => 'product-1',
'stock' => 5,
'available' => true,
'minPurchase' => 1,
'maxPurchase' => 10,
'isCloseout' => false,
]);
It is also possible to provide arbitrary data via extensions:
$stockData = \Shopware\Core\Content\Product\Stock\StockData::fromArray([
'productId' => 'product-1',
'stock' => 5,
'available' => true,
]);
$stockData->addArrayExtension('extraData', ['foo' => 'bar']);
The values in the StockData
instance will be used to update the loaded product instance. Furthermore, fetching the StockData
instance from the product via the stock_data
extension is possible. For example:
$stockData = $product->getExtension('stock_data');