Entities
Entities are crucial parts of backend APIs. A developer should be able to easily create an entity with a configuration file. An example can be as follows:
entity.fields.json
{
"fields": [
{
"name": "name",
"type": "string",
"options" : {
"length": 255,
"notNull": false
}
},
{
"name": "surname",
"type": "string",
"options" : {
"length": 255,
"notNull": false
}
},
{
"name": "password",
"type": "string",
"options" : {
"length": 255,
"notNull": false
}
},
{
"name": "email",
"type": "string",
"options": {
"unique": true
}
},
{
"name": "created_at",
"type": "integer"
},
{
"name": "updated_at",
"type": "integer"
},
{
"name": "active",
"type": "boolean"
}
]
}
After adding this to a custom module, the system should recognize this as an entity and automatically behave as one. The advantage of it is to create CRUD endpoints out of the box. The above example is for the user entity. Even though we don’t add anything in the routing.json config file, the system creates the POST, PUT, GET and DELETE endpoints with /user and /user/{id}, and also handles the permissions automatically.
Automatic permission handling
If we create a new entity such as articles, system checks for the following permissions for each request out of the box
- An authenticated user can create an article
- Authenticated users can edit their own article
- Authenticated users can delete their own article
- Authenticated users can list everyone’s articles.
Note: Of course this is a bit different for the user entity since an Anonymous user should also be able to create a user entity for registration.
We can always add additional routing.json files and schema.json files under entities to extend their capabilities.
Out of the box endpoints
- GET /entity_name/1: Returns the entity with all its attributes whose id is 1. Of course, clients should have necessary permissions to access this entity. Also we do not want to return the password fields so they will be excluded automatically.
- GET /entity_name: List all the entities exist.
- POST /entity_name: Creates a new entity. The request must contain all the entity fields data.
- PUT /entity_name/1: Update the entity with the id 1, with the posted data.
- DELETE /entity: Delete the entity. The request must contain the identifiers.
Loading an entity
Create a new entity without loading an id
$game = new game;
Load and entity with id
$game = new game(1);
or
$game = new game;
$game->load(1);