I have long standing argue about dependency injection and SOLID principles with my teammate. We both want to make an Exporter, to export data into various formats. My approach (in PHP):
class Exporter {
public function __construct(private WriterContract $writer)
{
}
public function export(): void {
// Do stuff and assign to $data
$this->writer->write($data);
}
}
class ExportController {
public function __construct(private Exporter $exporter) {
}
public function route(Request $request): Response {
$this->exporter->export();
return Response(200, ['success!'])
}
}
Teammates approach:
class Exporter {
public function __construct(private WriterContract $writer)
{
}
public function export(): Data {
// Do stuff and assign to $data
return $data;
}
}
class ExportController {
public function __construct(private Exporter $exporter, private WriterContract $writer) {
}
public function route(Request $request): Response {
$data = $this->exporter->export();
$this->writer->write($data);
return Response(200, ['success!'])
}
}
I think none of approaches is really bad, they just have different pros and cons. My approach is easier to use for a client, but adds extra dependency to the Exporter class. Teammates approach doesn't add extra dependency, but next developer who comes after my teammate needs to better know how to use it, because writer is now his responsibility. And Writer dependency is in fact only moved to a Client, so I don't see a real benefit here.
What do you think? Is any of these two approaches cleaner or objectively better? Am I missing any other approach?