This class' function is to change a given array's data into an ID. The list is set by a configuration file. I have DI the outer array and objects into the class so that if there are any dependencies - it gets injected.
The protected $_api;
is an external API class that contains some API call to an external address that will do a look up given type and value. It returns an ID and if there is a rare chance that it doesn't - it will return null.
redis
is a redis object that communicates with redis (it's being instantiated with a known lib so the set/get that you will see in the code are known).
table
is the list of tables being looked up.
2 steps:
Go find in redis and see if the hash value is there - if it is we get the ID and we move on.
If it is not there - go call the API and fetch it, and insert it into redis
My code used to pass the function getID
and have that function do the look up / API call, however since I need several values - I decided to do mGET
to get multiple values and only make one trip to redis.
The code works, however, I want to transform it to something better utilizing SOLID, and that's where the mGET
got me and I'm stuck. I figure that after writing this code I can see it, but I can't which is what I need help on.
class LookUp
{
protected $_api;
protected $_redis;
protected $_tables_switch_id;
public function __construct(\Redis $redis, Api\Track $api, $tables = array())
{
$this->_api = $api;
$this->_redis = $redis;
$this->_tables_switch_id = $tables;
}
public function changeDataIntoId($data)
{
$hash_value = array();
$index_array = array();
foreach ($this->_tables_switch_id as $index => $table) {
if (isset($data[$index])) {
$hash_value[$index] = md5(serialize(array($index => strtolower($data[$index]))));
$index_array[] = $index;
}
}
$ids = $this->_redis->mGet($hash_value);
$i = 0;
foreach ($ids as $id) {
$breakdown = $index_array[$i];
if ($id !== false) {
$data[$breakdown] = $id;
} else {
$api_id = $this->_api->getBreakdownID($breakdown, $data[$breakdown]);
if ($api_id == null) {
$api_id = 0;
}
$this->_redis->set($hash_value[$breakdown], $api_id);
$data[$breakdown] = $api_id;
}
$i++;
}
return $data;
}
}
One observation that might confuse you: why do I have two arrays.
One is the hash data, and the other one is an index. The entering data ($data
) could be composed of numerous indexes. I'm only converting those who are from $table
. This is the sole reason why I must retain the list and why I am also checking for isset
.