11. ORM introduction

Each ORM class represents a single database table, and each class instance represents a row in that table. To define an ORM class, you don’t need to extends any framework class, but just use the trait metadigit\core\db\orm\EntityTrait and fill the class code with proper annotation tags.

<?php
namespace myproject\model;

/**
 * @orm(source="users")
 */
class User {
	use \metadigit\core\db\orm\EntityTrait;

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

	/**
	 * @orm(type=”boolean”)
	 */
	protected $active = false;

	/**
	 * @orm
	 */
	protected $name;

	/**
	 * @orm
	 */
	protected $surname;

	/**
	 * @orm(type=”integer”)
	 * @validate(min=18)
	 */
	protected $age;

	protected $fullName;

	function onInit() {
		$this->fullName = $this->name . ‘ ‘ . $this->surname;
	}
}

After having defined the ORM class, you must define its Repository, which is the object you use to manage the models (CRUD operations). You can simply use the predefined Repository implementation which is metadigit\core\db\orm\Repository, passing the ORM class name to its constructor:

$UserRepository = new \metadigit\core\db\orm\Repository(‘myproject\model\User’);

You are encouraged to use Dependency Injection everywhere in your code, so you can define the repositories in a context.xml as the following:

<?xml version="1.0" encoding="UTF-8"?>
<context namespace="myproject.model">
	<objects>
		<!-- REPOSITORIES -->
		<object id="myproject.model.UserRepository" class="metadigit\core\db\orm\Repository">
			<constructor>
				<arg name="class">myproject\model\User</arg>
			</constructor>
		</object>
	</objects>
</context>