Drupal commerce - multiple shipments
Blog

Drupal Commerce: Splitting a package into multiple shipments using Packer & PackerManager

Drupal 8 commerce shipping contributed module introduced an extendable and prioritized concept of Packer and PackerManager. Packer allows sites to automatically split an order into multiple shipments based on stock location, weight, dimensions, or some other criteria.

Let’s see what Packer and PackerManager do.

Packer and PackerManager

  1. Packer: Creates one or more shipments for a given order. We can create an end number of Commerce Packer class, which implements `Drupal\commerce_shipping\Packer\PackerInterface`. PackerInterface provides abstract methods:
    1. applies: Determines whether the packer applies to the given order.
    2. pack: Packs the given order.
  1. PackerManager: Runs the added packers one by one until one of them returns a result.

How PackerManager works

Based on each Packer priority, PackerManager will check whether the packer applies for an order or not. If packer applies for the concerned order than it will execute the pack method. This iteration will go on until any one of the Packer returns a proposed shipment.

Commerce shipping contributed module implement DefaultPacker, which creates a single shipment per order. If we have implemented one or more Packer classes, then we have to prioritize the packers.

Implementing multiple shipments

  1. Create Packer class.

  2. Implement applies method, here this custom packer doesn’t apply to China location.

  3. Implement pack method.

  4. Tag Packer in module services.yml

Finally, Packer class will be as below:

That’s it! This is how we split the package into multiple shipments in Drupal 8 Commerce. The method that I espouse above is all about creating a good experience for customers. We recommend you to try out Packer and PackerManager concept to find out what works well for your ongoing projects.