Reputation: 2506
As a PHP dev, most of my projects are database-driven. I'm a fond lover of OOP & while new to the object world, I attempt to follow best practices to improve on my abilities.
If I have an object that requires information from my database, how is that object loosely coupled because it is heavily reliant on the returning results of the database?
Code example:
<?php
class Test {
protected $repository;
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
public function process()
{
$results = $this->repository->where('id', 1)->get();
( ! empty($results) ) ?: ''; // do something bad.
foreach ($results as $result) {
// This is my problem, my class now knows it needs an array key of name to be available.
// Is this bad?
echo $result['name'];
}
}
}
Here, my class is expecting an array key of name. This just feels wrong to me, because now my class is tightly coupled to the result set...
I have been doing a lot of reading on application layers, such as the domain layer, service layer, transaction scripts, application layer etc.
Even equipped with this knowledge I cannot see a solution to my problem.
It would be great to hear your thoughts on whether I'm driving myself mad for no reason.
It would also be great to see some code examples or further reading materials, books etc links.
Upvotes: 1
Views: 75
Reputation: 6404
I think you may be going too extreme with this. I wouldn't spend too much time trying to figure out how the repo can not know that you have a key called name. Someone will have to depend on that somewhere in your code and I don't think your repo class is a bad place to put that.
In the end, your goal should just be to save you and the maintainers of this codebase time when implementing new features, business rules or fixing bugs. And in my experience you can do this by isolating the parts of your application that you can foresee being complex or changing a lot.
So I wouldn't worry about the repo knowing the name of a key in the result set unless that key needed to be changed a lot, or if retrieving data from the result set was going to be a complex process.
Upvotes: 2