3

I understand that I can create an object using the ObjectManager through either its get() or create() method.

From the docs, create() will always create a new instance whereas get() retrieves a cached version of an object instance.

My chain of thoughts are:

  • I wouldn't know whether an object has already been created somewhere else in the cache, would I?
  • If I don't know whether an object is already in the cache, how do I know when I should use create() or get() method when creating an object? Will I end up creating multiple objects?

  • One possible use of get() I can think of is for singleton classes as they don't need to be created again. However, being new to Magento2, how would I know whether an object I want to create is an singleton or not? Similarly, will I end up creating multiple objects?

1
  • Use as much as possible dependency injection (DI) and avoid object manager. And use factories or proxy. The oject manager is use for the bootstrapping process. Commented Nov 17, 2016 at 11:01

1 Answer 1

1

ObjectManager get():

Used for a singleton object, when you want to use previously set object through out the code you can use get().

ObjectManager create();

create() will create each time a new object.

So, as per your requirements you can use get() or create().

Ex. if you want to use quote data you need to use old object so you can use get() and when you want to use your custom model and save data you can use create().

You can share code model's object with get().

2
  • Will I come to a situation where an object could already be created elsewhere but I don't know about it and need to check whether that object is already cached before I know I should use create() or get()?
    – xenon
    Commented Nov 17, 2016 at 9:29
  • if you are using core model than you can use get() even if will not get any value you will have an object so you can setdata in that object Commented Nov 17, 2016 at 9:34

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.