Object Override Code Doesn't Work For New Instances


I have been extending DataObjects using the model override described here. However, I’ve been experiencing an issue where newly created instances don’t have access to the override methods.

For example, the following code causes the error “Call to undefined method overrideMethod in class Pimcore\Model\DataObject\Item”:

$item = new Item();

but when instances are retrieved via the API, like in the following code, I get no errors.

$item = Item::getById($id);

I have looked in the documentation to try and figure out why this would be the case, but cannot see anything that mentions this particular hiccup that I’ve been experiencing.

Does anyone have any thoughts on why I’ve been having this error?



the problem is that using new you create a new instance of Pimcore\Model\DataObject\Item. If you want to use new you SHOULD create a new instance of AppBundle\Model\DataObject\Item. So:

  • new \Pimcore\Model\DataObject\Item() - still creates a Pimcore default object
  • new \AppBundle\Model\DataObject\Item - creates your object

However, as far as I know, it is a good practice to don’t create an object by new but set them as a parameter and use Symfony autowire functionality - it can help in Unit Testing.

PS: When you use \Pimcore\Model\DataObject\Item::getById($id) Pimcore probalby reads the overrided configuration and that’s why you have got \AppBundle\Model\DataObject\Item

PS2: If you want you can probably also use \Pimcore\Model\DataObject\Item::create() to have your \AppBundle\Model\DataObject\Item as a result

1 Like

IMHO: Don’t use the magic overrides for Pimcore Objects, they result in Problems like you have. Rather use parent-class in objects and implement your custom functions there.

1 Like

Thanks for the responses, the Item::create() is exactly what I was looking for!

I appreciate the other suggestions as well, but that one’s the easiest to implement with my current setup while resolving all of the issues I was having.


An unfortunate follow up to this issue:

While initially Item::create() did work as a way to specifically retrieve new instances of Item with the override methods, after a couple of hours the behavior changed and objects created with Item::create(), were no longer of type ‘/AppBundle/Mode/DataObject/Item’ but were ‘/Pimcore/Mode/DataObject/Item’. I don’t know why this happened, but was able to temporarily fix it with a cache clear.

I have just started doing /AppBundle/Mode/DataObject/Item::create() when I need to create a new instance, and only for new instances, because when specifically referencing the override version I no longer have access to the Listing Class which is namespaced at ‘/Pimcore/Mode/DataObject/Item/Listing’. I could probably override the listing classes too, but at this point I’m just going to stick to what works long term.