I have been working on refactoring some code I wrote a while back to be cleaner and more testable. I may be splitting hairs here but for the scenario below I am wanting to know which approach is better and why.
So I have an Observer that watches my App model created event, and then performs some initialization. In one scenario, I can simply invoke my initializer directly, and in another I can call initialize on my model and pass in an Initializer object.
The Observer: AppObserver.php
class AppObserver {
private $appInitializer;
public function __construct(InitializerInterface $appInitializer){
$this->appInitializer = $appInitializer;
}
public function created($app) {
// option 1
$this->appInitializer->initialize($app);
// option 2
$app->initialize($this->appInitializer);
}
}
The Model: App.php
class App {
...
// option 2
public function initialize(InitializerInterface $initializer){
$initializer->initialize($this);
}
...
}
The Initializer: AppInitializer.php
class AppInitializer implements InitializerInterface {
...
public function initialize($app){
$this->generateIdHash();
$this->generateSecretKey();
$this->setPlatformVersion();
}
...
}
I am leaning towards Option 2 because it would allow me to do other stuff that the Initializer dependency doesn't do.
I appreciate any feedback you give, and or any suggestions you have.
Option 2 has a two way dependency. The initializer must knows about the app in both options, but in option 2 the app must know about the initializer. Although you've used an interface, so it's not that bad.
But still on the face of it, without any other information or requirements I'd go with option 1 as the cleaner option.
You say option 2 allows you to do more, this might be true, but I'd wait and see what more you need it to do.