C
C
cheremushkin2012-07-31 21:43:12
PHP
cheremushkin, 2012-07-31 21:43:12

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

7 answer(s)
S
serso, 2012-07-31
@cheremushkin

If these are utility methods (sorting, formatting, etc.), then it's normal practice to make them static.

N
Nazar Mokrinsky, 2012-07-31
@nazarpc

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.

E
EugeneOZ, 2012-08-03
@EugeneOZ

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).

I
Igor, 2012-07-31
@igoravr

Registry Design Pattern

D
DanielWolf, 2012-08-01
@DanielWolf

Pattern Singleton (Singleton)
http://ru.wikipedia.org/wiki/Single_(design_pattern)
or rather the Pool of singletons (Multiton / Registry of singletons).

A
Anatoly, 2012-08-01
@taliban

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 =)

V
Vyacheslav Plisko, 2012-08-01
@AmdY

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 question

Ask a Question

731 491 924 answers to any question