How to create a single object for all functions in Yii2

I created a repository pattern class in my Yii2 project, and I’m creating a new object from the model for all functions, what is the best way to create only one object from the model and use it in all functions?

Hi Mhd_Mazon. Sorry, but didn’t get what your goal. Are you trying to understand the best design patterns to use with Yii2?
Could you give some more details?

Thank you for your reply,
I just need to create one object from my model to use in all the functions.

Assume I created an object from the user model,

$model = new User();
What I actually need is to use this object on every function in the same class, so function a, b and c can use the variable $model.

I just need this step to switch between MongoDB and MySQL, So when I want to use mongo, I need to change the object only and everything works well.

If you just need to reference this model in your class, just set the variable in the class scope. Set it in the constructor or with a setter.

But if what you need is to use this model throughout your application, you should use the Singleton pattern, which there’s more info in this link: https://www.yiiframework.com/doc/guide/2.0/en/concept-di-container#registering-dependencies

The example is close to the scenario you told us and is the one I would chose to implement.