Let's say I have something like this
Controller
usesService
.Service
hasHistory
,Source
andHttpClient
.Source
hasSourceRepository
andid
.Source
is only useful for other objects after fetching information fromSourceRepository
.
History
hasHistoryRepository
andSource
.
Below is a mixture of PHP + pseudocode (for the sake of simplicity) to ilustrate this scenario.
public class Source
{
...
public function __construct(InterfaceRepository $repository, int $id)
{
$this->data = $this->repository->findById($id);
}
}
public class History
{
...
public function __construct(InterfaceRepository $repository, InterfaceSource $source)
{
...
}
public function hasHistory(): bool
{
return $this->repository->exists($this->source->data);
}
public function duplicateHistory()
{
...
}
}
public class Service
{
...
public function __construct(InterfaceHistory $history, InterfaceSource $source, InterfaceHttpClient $httpClient)
{
...
}
public function send()
{
if ($this->history->hasHistory()) {
return $this->history->duplicateHistory();
}
return $this->sendNewRequest();
}
public function sendNewRequest()
{
$this->httpClient->postRequest($this->source->data);
}
}
public class Controller
{
public function doSomething(int $id)
{
$sourceRepository = new SourceRepository();
$source = new Source($sourceRepository, $id);
$historyRepository = new HistoryRepository();
$history = new History($historyRepository, $source);
$httpClient = new Guzzle();
$service = new Service($history, $source, $httpClient);
$service->send();
}
}
Now I have some questions regarding Dependency Injection:
- Should all object building really stay in the highest level, in this case the
Controller
?- Or are there cases where some of the object building is in the middle layers?
- If I was to use a Dependency Injection Container, I think it wouldn't be able to instantiate
Source
because ofid
. How should I solve this?