Skip to content

Instantly share code, notes, and snippets.

@makoru-hikage
Created October 21, 2016 06:14
Show Gist options
  • Save makoru-hikage/438ef507f578e35583d6a33303fa7eaa to your computer and use it in GitHub Desktop.
Save makoru-hikage/438ef507f578e35583d6a33303fa7eaa to your computer and use it in GitHub Desktop.
The use of alternative ID system.
<?php
/**
* This is a simple search function by ID. An alternate ID(AID) key is a candidate key that
* is UNIQUE and is a natural key. This is used when surrogate keys are applied but a
* user want to search by a unique identifying name. Whilst primary keys(PK) called 'id'
* are UNSIGNED INT, the AID keys are usually VARCHAR. Such an example is a User entity.
* A user entity has 'id' as PK and 'username' as its AID. When someone wants to search
* by 'username'.
*
* This snippet requires Eloquent and Repofuck installed. To use this, the entity class
* must be a descendant of Model class and has $alternateIdKey property.
*/
/**
* Searches using the given id value.
*
* @param string $entityName
* @param string|int $idvalue
* @return Model|null $entity
*/
public function find($entityName, $idValue){
$repo = $this->repo;
//Finds the entity and chooses it from the repo.
if(!$this->resetEntity($entityName)){
return null;
}
if (is_numeric($idValue)){
//DECIMAL IDs DO NOT EXIST
$idValue = (int)$idValue;
$entity = $repo->find($idValue);
} else {
$alternateIdKey = $repo->entities->current()->getAlternateIdKey();
$entity = $repo->first($alternateIdKey,$idValue);
}
return $entity;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment