11.1 Model definition

Models are simple Php classes, with the unique requirement of using the trait:
\metadigit\core\db\orm\EntityTrait
The trait adds minimal required funtionalities to make the model works, by:

  • implementing magic methods construct(), get(), invoke(), set(), required to build, injecting & read values
  • define empy methods onInit(), onSave(), onDelete()

All the magic of ORM happens thanks to @doc annotations, without having to write php code or extending predefined class, so leaving your model class very simple and clean.

With the annotation tag @orm you can configure properties and overall model behaviour. Let's start with a simple User model:

<?php
namespace myproject\model;

/**
 * @orm(source="users")
 */
class User {
  use \metadigit\core\db\orm\EntityTrait;
  
  /**
   * @orm(type="integer", primarykey, autoincrement)
   */
  protected $id;

  /**
   * @orm(type="boolean")
   */
  protected $active = true;
}

@orm model annotation

The class annotation is required to define the "source" SQL table, in this example the table "users":

/**
 * @orm(source="users")
 */
class User {

Our ORM model can also support SQL views, with extended read only properties. In this case we have to define both the "source" and the "target" for SQL operations:

/**
 * @orm(source="users_view", target="users")
 */
class User {

The framework will use SQL table "users" for INSERT, UPDATE and DELETE queries, whereas the SQL view "users_view" for SELECT queries.

@orm properties annotation

Every model properties MUST have his @orm tag, which defines property type and optional features. Inside @orm tag, we can define multiple attributes:

/**
 * @orm(type="integer", primarykey, autoincrement)
 */
protected $id;

The @orm available attributes are:

  • @orm(type=”X”) where X can be: string, integer, float, boolean, date, datetime, object, array; its default is “string”.
  • @orm(primarykey) will make ORM capable of using this properties as a primary key (for FETCH ore DELETE operations).
  • @orm(autoincrement) will make ORM manage this primary key as an AUTO INCREMENT value.
  • @orm(null) the ORM will allow NULL value, automatically converting to NULL if value is not present.