How to handle and pass around an entity with multiple unique identifiers?

Member | 31

It happens to me all the time that I have some entity, let's say Tag and I have methods interacting with this entity. For example I need to assign a tag to a note (another entity) and this needs to happen on different places in the application and somewhere it's good to pass in the ID of the tag, other place I'd be nice to pass in the name of the tag (which is also a unique identifier) and somewhere I already have the exact instance of the tag entity which I could easily pass to the method.

Can you think of a nice solution to standardize this? For example I though that all my model methods could accept just the entity as a parameter but then in some cases I'd need to get the entity let's say byId just to pass it into another method which would use only the id parameter which feels odd to me.

Code example – not a perfect one:

// Somewhere in the application
$note = ...
$tagOld = $this->tagManager->getById(123);
$tagNew = $this->tagManager->getById(321);
$this->noteManager->replaceNoteTag($note, $tagOld, $tagNew)

public function replaceNoteTag(Note $note, Tag $tagOld, Tag $tagNew) {
   	// Let's say these accepts tag id

What is your strategy for handling these situations?
Thank you :)

PS: I'm using Nextras ORM but I'm sure that this applies anywhere.

Would it be a good strategy to just “get” the entity as soon as possible (highest layer of the application) and then just work with the entity in all the lower layers?
So for example get the entity in presenter and then all the other methods (in model) would just assume that you have the entity. Therefore the only methods that would accept entity id or name would be get[Entity]ById or get[Entity]ByName and everything else would work with entity instances.

Last edited by TonnyVlcek (2017-08-18 16:29)