Hamani: Entities and Repositories what is the difference?

140 Views Asked by At

I continue to study hanami on my own and I ran into the fact that when generating the User model, hanami generates 2 entities and repositories directories that contain files

user.rb in the entities directory

class User < Hanami::Entity
end

user_repositories.rb in the repositories directory

class UserRepository < Hanami::Repository
end

I read the documentation but I still did not understand in which of these classes the validation with associations should be described or why each of these classes is needed in principle, since in RoR we needed 1 model. please explain (

1

There are 1 best solutions below

1
On BEST ANSWER

Luca from Hanami here :)

Entities:

An entity is domain object that is defined by its identity.

An entity is at the core of an application, where the part of the domain logic is implemented. It’s a small, cohesive object that expresses coherent and meaningful behaviors.

Repository:

An object that mediates between entities and the persistence layer. It offers a standardized API to query and execute commands on a database.

In a nutshell: entities are your business logic and data holder, repositories are a way to read/write data from/to the database.

If you're familiar with Rail's ActiveRecord, it's like splitting a Rails model in two responsibilities: the one that implements the business logic, and the one that deals with the database.


Validations: we don't mix validations with models. You are encouraged to put validations in Interactors or in Actions.

The reason is explained in a blog post of mine. [Please note Hanami was formerly known as Lotus].