Answer the question
In order to leave comments, you need to log in
How to globally store an object?
I have several objects in my code whose methods I need in almost every other part of the program. But I don't want to create these objects all over again in all functions; I don't like to prescribe global either. It is also impossible to store in constants, there is only a scalar. But maybe there is another solution?
Of course, you can get by with the option of calling methods through :: (static), but I would like to find a more beautiful solution.
Answer the question
In order to leave comments, you need to log in
If these are utility methods (sorting, formatting, etc.), then it's normal practice to make them static.
You need to associate an object with certain sections of code, and you immediately cut off possible technical ways.
You can try storing in the APC cache (functions apc_store()/apc_fetch()) - but not sure if it will store objects correctly. Yes, and between requests, such a cache will save data.
Static methods, variables are the same as GLOBAL, and it stinks absolutely the same. And this has nothing to do with OOP - this is procedural programming.
If you want exactly OOP, do as is customary in OOP - pass an object (dependency injection) or use a trait, you can just use it and that's it.
And keep in mind - if an object is needed everywhere, simply because it has many different methods, then you need to check whether this object fulfills one responsibility (read about SOLID and the single responsibility principle).
Pattern Singleton (Singleton)
http://ru.wikipedia.org/wiki/Single_(design_pattern)
or rather the Pool of singletons (Multiton / Registry of singletons).
If you need an object as an entity, then create it everywhere, if you have a class as a set of functions, then make it static, and if you need the same object as an entity only once, then a global or a singleton. Everything is simple =)
I like the option with the service locator, I have it the only singleton in the framework, I pull everything else through it. The most important thing is that these services can be replaced at runtime or in tests, which cannot be said about globals or static methods.
I advise you to look at the article wiki.agiledev.ru/doku.php?id=ooad :dependency_injection
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question