I am beyond stuck in a half way point between PHP structural and OOP, but I can never achieve proper SOLID patterns despite reading DI, IOC, and reading about the interfaces.
Rather than to read logical examples (i.e. a storage class that takes a book class and you typecast an interface etc...). I want to know how I can take my brain off thinking I got SOLID down but I actually didn't. There is talk about trying to refactor a small chunk but then that small chunk isn't SOLID enough.
Here are the code segments - my thought and goals are after:
class DataID
{
protected $_id_array;
protected $_storage;
public function __construct(StorageInterface $db_conn, $tables = array())
{
$this->_storage = $db_conn;
foreach ($tables as $table) {
$sql = "SELECT `id` as `id`, `name` as `value` FROM $table ORDER BY `value` ASC";
$result = $this->_storage->read($sql);
if (!empty($result)) {
foreach ($result as $row) {
$this->_id_array[$table][$row['value']] = $row['id'];
}
}
}
}
public function getID($table, $value)
{
if (!empty($this->_id_array[$table])) {
if (isset($this->_id_array[$value])) {
return $this->_id_array[$table][$value];
}
}
return null;
}
}
Goal:
I have tables that has ID vs Value data. I'm going to use this class to run through data (value) and I want to retrieve the ID of it. Best way to avoid too many DB request is to put it inside an array of [value] = ID I believe and then check corresponding index as value and fetch ID.
Storage is an container that goes into the DB via SQL and go fetch me all the data over. This way if the method of the storage changes (Mongo, SQL, pod, MySQLi) I can change how I treat my read.
Tables is a list of known tables in the DB that I need that Data from. That list will be from an array config file that shall be loaded in a main.
Issues:
I have a strong feeling that I can make this better but I don't know how - because to me a constructor initialize things and well I'm going into the DB to initialize my array but for some reason i feel that SOLID fails for me here.
If I have tables that have too many values (i.e. let's say if a table look up is more than 50) I want to hit the DB and not store it inside an array.
If that's the case, I'll have to make queries inside getID
to use storage to go fetch it. How do I maintain SOLID while adding that extra logic?
getID
's secondif
. \$\endgroup\$