Let’s say you have a object that is unique, and it’s used by all other classes and functions …something like $application.
How would you access this object in your functions?
-
using a global variable in each of you functions:
global $application; $application->doStuff(); -
creating a function, like
application()that instantiates the object into a static variable and returns it; then use this function everywhere you need to access the object:application()->doStuff(); -
create a singleton thing, like a static method inside the object class which returns the only instance, and use this method to access the object:
Application::getInstance()->doStuff(); -
KingCrunch & skwee: Pass the application object as argument to each function/class where is needed
... public function __construct(Application $app, ...){ ....
If there are other options please post them. I’m wondering which of these options is the most efficient / considered “best practice”.
I’d pass it to all the needed methods.
i.e.
Both global and singleton considered bad and ties your code too much and this makes unit testing more difficult.
There is one rule when you are allowed to use singleton, if you answer “yes” to the following statement:
If you answer yes to all the 3 parts then you can use singleton. In any other case just pass all the instances to all the method who needs them. If you have too much of them, consider using something like Context
(you can use getters/setters if you need to protect the data or manipulate it or if you want to use lazy initiation etc).
Good luck!