Can anybody explain me why the right way for programmatically saving a line item object with Drupal Commerce is the following one?


I wish to be smarter after knowing that.

  • Presumably you mean "why does this code manually reset the entity cache? Shouldn't it be automatic?"
    – Clive
    Jul 15, 2016 at 15:25
  • Yes .... Why is this not automatic. I would expect the commerce_line_item_save to be be declared : function commerce_line_item_save(&$item), so that my code keeps clean : I don't to add a line to get the result I want. However, it has been designed this way, and there must be a reason, this is what I want to know.
    – jmary
    Jul 15, 2016 at 17:15

1 Answer 1


That isn't the right way to save a line item. All that second line does is remove the item from the entity controller's static cache.

As CommerceLineItemEntityController::save() already manipulates the static cache directly to ensure the updated entity is in it, the second line is redundant. All it does is force unnecessary database usage if/when the same line item is loaded again in the same request.

This is all you need to create or update a line item:


Remember that $item is an object, so doesn't need to be passed by reference as you mentioned in the comments.

  • That goes make me catch some concepts I was totally ignorant about : What is the static cache, comparing to other caches ? Also reading the code you linked I don' t see where the potential redundancy come ....
    – jmary
    Jul 15, 2016 at 17:38
  • Static cache is per-request, PHP provides it via the static keyword. It's different from other caches, e.g. database cache, because it doesn't persist beyond that single request. It's useful, for example, when more than one bits of code load an entity during one page load. The expensive database calls only happen once. The redundancy is actually in the parent method: $this->entityCache[$entity->{$this->idKey}] = $entity; from drupalcontrib.org/api/drupal/…
    – Clive
    Jul 15, 2016 at 17:47
  • I come from C world (not C++) ... so when you know that you will need something later, you pass it by reference or create a new variable that you follow (second is safer), and moving pointers costs nothing. That probably whyI' m a bit lost here ...
    – jmary
    Jul 15, 2016 at 18:04
  • Yeah I came from the same world, php is...interesting :)
    – Clive
    Jul 15, 2016 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.