Skip to content

Instantly share code, notes, and snippets.

@dustinsgoodman
Last active November 22, 2020 17:26
Show Gist options
  • Save dustinsgoodman/3adafe3ec4e9b4d38a4cd763790aa0ff to your computer and use it in GitHub Desktop.
Save dustinsgoodman/3adafe3ec4e9b4d38a4cd763790aa0ff to your computer and use it in GitHub Desktop.
PHP Cache Blog - Mistake 2
<?php
namespace MyObject;
use Utils\ArrayUtils as _; // basically lodash
class DAO extends \Base\MySQL\DAO {
// ...
/**
* Lookup MyObject entities by relationship A. Can additionally filter by relationship B OR C.
*
* @param int|int[] $relationAId ID(s) of the main relationship we're looking up
* @param int|int[]|null $relationBId ID(s) of relationship B
* @param int|int[]|null $relationCId ID(s) of relationship C
*
* @return MyObject|MyObject[] list of matching records
* @throws \Exception
*/
public static function getByRelation($relationAId, $relationBId = null, $relationCId = null) {
$result = self::getDAOCache()->getByForeignKey(MyObject::$FK_RELATION_A, $relationAId);
if (isset($relationBId)) {
if (empty($relationBId)) {
return [];
}
// if relationBId exists, cast to an array
$relationBId = _::castArray($relationBId);
$result = _::filter($result, function ($item) use ($relationBId) {
// check using contains instead of ===
return _::contains($relationBId, $item->relationBId);
});
} else if (isset($relationCId)) {
if (empty($relationCId)) {
return [];
}
// if relationCId exists, cast to an array
$relationCId = _::castArray($relationCId);
$result = _::filter($result, function ($item) use ($relationCId) {
// check using contains instead of ===
return _::contains($relationCId , $item->relationCId);
});
}
if ((!$relationBId && !$relationCId) || is_array($relationAId)) {
return $result;
}
if (count($result) > 1) {
throw new \Exception("Ambiguous object for relationA $relationAId, relationB $relationBId");
}
return _::first($result);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment