Is there a good practice way of making communication between classes?
For example, I have a CMS I'm working on. In main class it instantiates two new Classes ThemeManager and ModuleManager. Now, I need my Theme Manager to be able to access Module Manager so that it can read loaded modules and print their content in a page.
Is this OK ? Making these two classes public properties of main class. This enables me two-way communication (which I don't necessarily need in this situation):
class MainClass {
public $ThemeManager;
public $ModuleManager;
..........
function instantiate_managers() {
$this->ThemeManager = new ThemeManager($this);
$this->ModuleManager = new ModuleManager($this);
}
}
Or is it this better? Passing one already instantiated to another, since one-way communication will do OK for my purpose:
class MainClass {
private $ThemeManager;
private $ModuleManager;
..........
function instantiate_managers() {
$this->ModuleManager = new ModuleManager();
$this->ThemeManager = new ThemeManager($this->ModuleManager);
}
}
Note that in either way I have to pass these references further to Module class and Theme -> Layout classes.
Maybe it would be better to declare ThemeManager and ModuleManager in global scope since they will be instantiated only once anyway and saves me the trouble of passing their references through each __construct ? I've read somewhere that this is bad practice in OOP and I'm trying to avoid it, but in situations like these this seems like the least hacky way to do it.
Is there a 4th good way to handle communication which I haven't tought about?
Answer
I ended up using Pimple for dependency injection method since it felt most natural and was suggested in both answers.
