Why you should use entity instead of directy database records

Tags:

Before we explain why entity must be used, first learn what is entity. Entity is class presentation of database table, where each properties of class represents database column. Nishchay allows defining data type for the property so that when record is fetched from database it gets converted to data type as specified on class property.

Entity Manager

Entity manager makes entity class to interact with database table to which its associated with. Entity manager allows fetching and managing database records. Suppose we have entity class User then it can be used as follows:

$userEntity = new EntityManager(User:class);
Reasons to choose entity
Data type

Entity manager converts fetched record to its data type as specified in entity class property.

Validation

This also provides validation for the property. Entity prevents invalid data to be assigned to property.

Custom validation

We can define our on validation for any properties within entity class.

Events

We can create events which can be called on action like before/after update, insert and delete.

Relationship

We can relate one entity to another entity. This also adds validation for property and it won't allow property to have value which does not exists in parent entity.

Derived properties

Derived properties allows fetching properties from another property.