ORM

The Pagekit Object-relational mapper (ORM) helps you create model classes of your application data where each property is mapped to the according table column automatically. You can also define relations between your entities and the existing entities from Pagekit (i.e. users)

Setup

Create tables

Run the following, i.e. in the install hook of your extension's scripts.php. For more general information on creating tables, have a look at the database chapter.

Example:

  1. $util = $app['db']->getUtility();
  2.  
  3. if ($util->tableExists('@forum_topics') === false) {
  4. $util->createTable('@forum_topics', function ($table) {
  5. $table->addColumn('id', 'integer', ['unsigned' => true, 'length' => 10, 'autoincrement' => true]);
  6. $table->addColumn('user_id', 'integer', ['unsigned' => true, 'length' => 10, 'default' => 0]);
  7. $table->addColumn('title', 'string', ['length' => 255, 'default' => '']);
  8. $table->addColumn('date', 'datetime');
  9. $table->addColumn('modified', 'datetime', ['notnull' => false]);
  10. $table->addColumn('content', 'text');
  11. $table->addIndex(['user_id'], 'FORUM_TOPIC_USER_ID');
  12. $table->setPrimaryKey(['id']);
  13. });
  14. }

Define a Model class

Example:

  1. <?php
  2. namespace Pagekit\Forum\Model;
  3. use Pagekit\Database\ORM\ModelTrait;
  4. /**
  5. * @Entity(tableClass="@forum_topics")
  6. */
  7. class Topic
  8. {
  9. use ModelTrait;
  10. /** @Column(type="integer") @Id */
  11. public $id;
  12. /** @Column */
  13. public $title = '';
  14. /** @Column(type="datetime") */
  15. public $date;
  16. /** @Column(type="text") */
  17. public $content = '';
  18. /** @Column(type="integer") */
  19. public $user_id;
  20. /**
  21. * @BelongsTo(targetEntity="Pagekit\User\Model\User", keyFrom="user_id")
  22. */
  23. public $user;
  24. }

A model is a plain PHP class that uses the trait Pagekit\Database\ORM\ModelTrait. Traits allow to include certain behaviour into a class - similar to simple class inheritance. The main difference is that a class can use multiple traits while it could only inherit from one single class.

Note If you are unfamiliar with traits, have a quick look at the official PHP documentation on traits.

The annotation @Entity(tableClass="@my_table") binds the Model to the database table pk_my_table (@ is automatically replaced by the database prefix of your installation )

Annotations will only work if you start the multiline comment with two asterisks, not just with one.

  1. // will NOT work:
  2. /* @Column */
  3. // will work:
  4. /** @Column */
  5. // will work:
  6. /**
  7. * @Column
  8. */

When defining a property in a class, you can bind that variable to a table column, by putting the /* @Column(type="string") / annotation right above the property definition. You can use any types supported by Doctrine DBAL.

The class you reference in your model class also has to exist in the database.

Relations

The application data you represent in your database model has certain relations amongst its instances. A blog post has a number of comments related to it and it belongs to exactly one User instance. The Pagekit ORM offers mechanisms to define these relations and also to query them in a programmatic manner.

Belongs-to relation

The basic annotation that is used across the different relation types is the @BelongsTo annotation above a model property. In the following example (taken from the Post model of the Blog) we specify a $user property, which is defined to point to the instance of the Pagekit User model.

The keyFrom parameter specify which source property is used to point to the user id. Note how we also need to define the according user_id property in order for the relationship to be resolved by a query.

Example:

  1. /** @Column(type="integer") */
  2. public $user_id;
  3. /**
  4. * @BelongsTo(targetEntity="Pagekit\User\Model\User", keyFrom="user_id")
  5. */
  6. public $user;

One-to-many relation

In this relationship, a single model instance has references to an arbitraryamount of instances of another model. A classic example for this is a Postwhich has any number of Comment instances that belong to it. On the inverseside, a comment belongs exactly one Post.

Example from the blog package, in Pagekit\Blog\Model\Post.

  1. /**
  2. * @HasMany(targetEntity="Comment", keyFrom="id", keyTo="post_id")
  3. */
  4. public $comments;

Define the inverse of the relation in Pagekit\Blog\Model\Comment:

  1. /** @Column(type="integer") */
  2. public $post_id;
  3. /** @BelongsTo(targetEntity="Post", keyFrom="post_id") */
  4. public $post;

To query the Model, you can use the ORM class.

  1. use Pagekit\Blog\Post;
  2. // ...
  3. // fetch posts without related comments
  4. $posts = Post::findAll();
  5. var_dump($posts);

Output:

  1. array (size=6)
  2. 1 =>
  3. object(Pagekit\Blog\Model\Post)[4513]
  4. public 'id' => int 1
  5. public 'title' => string 'Hello Pagekit' (length=13)
  6. public 'comments' => null
  7. // ...
  8. 2 =>
  9. object(Pagekit\Blog\Model\Post)[3893]
  10. public 'id' => int 2
  11. public 'title' => string 'Hello World' (length=11)
  12. public 'comments' => null
  13. // ...
  14. // ...
  1. use Pagekit\Blog\Post;
  2. // ...
  3. // fetch posts including related comments
  4. $posts = Post::query()->related('comments')->get();
  5. var_dump($posts);

Output:

  1. array (size=6)
  2. 1 =>
  3. object(Pagekit\Blog\Model\Post)[4512]
  4. public 'id' => int 1
  5. public 'title' => string 'Hello Pagekit' (length=13)
  6. public 'comments' =>
  7. array (size=0)
  8. empty
  9. // ...
  10. 2 =>
  11. object(Pagekit\Blog\Model\Post)[3433]
  12. public 'id' => int 2
  13. public 'title' => string 'Hello World' (length=11)
  14. public 'comments' =>
  15. array (size=1)
  16. 6 =>
  17. object(Pagekit\Blog\Model\Comment)[4509]
  18. ...
  19. // ...
  20. // ...

One-to-one relation

A very simple relationship is the one-to-one relation. A ForumUser might have exactly one Avatar assigned to it. While you simply include all information about the avatar inside the ForumUser model, it sometimes makes sense to split these in separate models.

To implement the one-to-one relation, you can use the @BelongsTo annotation in each model class.

/* @BelongsTo(targetEntity="Avatar", keyFrom="avatar_id", keyTo="id") /

  • targetEntity: The target model class
  • keyFrom: foreign key in this table pointing to the related model
  • keyTo: primary key in the related modelExample model ForumUser:
  1. <?php
  2.  
  3. namespace Pagekit\Forum\Model;
  4.  
  5. use Pagekit\Database\ORM\ModelTrait;
  6.  
  7. /**
  8. * @Entity(tableClass="@forum_user")
  9. */
  10. class ForumUser
  11. {
  12.  
  13. use ModelTrait;
  14.  
  15. /** @Column(type="integer") @Id */
  16. public $id;
  17.  
  18. /** @Column */
  19. public $name = '';
  20.  
  21. /** @Column(type="integer") */
  22. public $avatar_id;
  23.  
  24. /** @BelongsTo(targetEntity="Avatar", keyFrom="avatar_id", keyTo="id") */
  25. public $avatar;
  26.  
  27. }

Example model Avatar:

  1. <?php
  2.  
  3. namespace Pagekit\Forum\Model;
  4.  
  5. use Pagekit\Database\ORM\ModelTrait;
  6.  
  7. /**
  8. * @Entity(tableClass="@forum_avatars")
  9. */
  10. class Avatar
  11. {
  12.  
  13. use ModelTrait;
  14.  
  15. /** @Column(type="integer") @Id */
  16. public $id;
  17.  
  18. /** @Column(type="string") */
  19. public $path;
  20.  
  21. /** @Column(type="integer") */
  22. public $user_id;
  23.  
  24. /** @BelongsTo(targetEntity="ForumUser", keyFrom="user_id", keyTo="id") */
  25. public $user;
  26.  
  27. }

To make sure the related model is included in a query result, fetch the QueryBuilder instance from the model class and explicitly list the relation property in the related() method.

  1. <?php
  2.  
  3. use Pagekit\Forum\Model\ForumUser;
  4. use Pagekit\Forum\Model\Avatar;
  5.  
  6. // ...
  7.  
  8. // get all users including their related $avatar object
  9. $users = ForumUser::query()->related('avatar')->get();
  10. foreach ($users as $user) {
  11. var_dump($user->avatar->path);
  12. }
  13.  
  14. // get all avatars including their related $user object
  15. $avatars = Avatar::query()->related('user')->get();
  16. foreach ($avatars as $avatar) {
  17. var_dump($avatar->user);
  18. }

Many-to-many relation

Sometimes, two models are in a relation where there are potentially many instances on both sides of the relation. An example would be a relation between tags and posts: One post can have several tags assigned to it. At the same time, one tag can be assigned to multiple posts.

A different example that is listed below, is the scenario of favorite topics in a discussion forum. A user can have multiple favorite topics. One topic can be favorited by multiple users.

To implement the many-to-many relation, you need an additional database table. Each entry in that table represents a connection from a Topic instance to a ForumUser instance and vice versa. In database modelling, this is called a junction table.

Example tables (i.e. in scripts.php):

  1. $util = $app['db']->getUtility();
  2. // forum user table
  3. if ($util->tableExists('@forum_users') === false) {
  4. $util->createTable('@forum_users', function ($table) {
  5. $table->addColumn('id', 'integer', ['unsigned' => true, 'length' => 10, 'autoincrement' => true]);
  6. $table->addColumn('name', 'string', ['length' => 255, 'default' => '']);
  7. $table->setPrimaryKey(['id']);
  8. });
  9. }
  10. // topics table
  11. if ($util->tableExists('@forum_topics') === false) {
  12. $util->createTable('@forum_topics', function ($table) {
  13. $table->addColumn('id', 'integer', ['unsigned' => true, 'length' => 10, 'autoincrement' => true]);
  14. $table->addColumn('title', 'string', ['length' => 255, 'default' => '']);
  15. $table->addColumn('content', 'text');
  16. $table->setPrimaryKey(['id']);
  17. });
  18. }
  19. // junction table
  20. if ($util->tableExists('@forum_favorites') === false) {
  21. $util->createTable('@forum_favorites', function ($table) {
  22. $table->addColumn('id', 'integer', ['unsigned' => true, 'length' => 10, 'autoincrement' => true]);
  23. $table->addColumn('user_id', 'integer', ['unsigned' => true, 'length' => 10, 'default' => 0]);
  24. $table->addColumn('topic_id', 'integer', ['unsigned' => true, 'length' => 10, 'default' => 0]);
  25. $table->setPrimaryKey(['id']);
  26. });
  27. }

The relation itself is then defined in each Model class where you want to be able to query it. If you only want to list the favorite posts for a specific user, but you do not lists all user who have favorited a given post, you would only define the relation in one model. In the following example however, the @ManyToMany annotation is located in both model classes.

The @ManyToMany annotation takes the following parameters.

ArgumentDescription
targetEntityThe target model class
tableThroughName of the junction table
keyThroughFromName of the foreign key in "from" direction
keyThroughToName of the foreign key in "to" direction
orderBy(optional) Order by statement

Example annotation:

  1. /**
  2. * @ManyToMany(targetEntity="ForumUser", tableThrough="@forum_favorites", keyThroughFrom="topic_id", keyThroughTo="forum_user_id")
  3. */
  4. public $users;

Example model Topic:

  1. <?php
  2.  
  3. namespace Pagekit\Forum\Model;
  4.  
  5. use Pagekit\Database\ORM\ModelTrait;
  6.  
  7. /**
  8. * @Entity(tableClass="@forum_topics")
  9. */
  10. class Topic
  11. {
  12.  
  13. use ModelTrait;
  14.  
  15. /** @Column(type="integer") @Id */
  16. public $id;
  17.  
  18. /** @Column */
  19. public $title = '';
  20.  
  21. /** @Column(type="text") */
  22. public $content = '';
  23.  
  24. /**
  25. * @ManyToMany(targetEntity="ForumUser", tableThrough="@forum_favorites", keyThroughFrom="topic_id", keyThroughTo="forum_user_id")
  26. */
  27. public $users;
  28.  
  29. }

Example model ForumUser:

  1. <?php
  2.  
  3. namespace Pagekit\Forum\Model;
  4.  
  5. use Pagekit\Database\ORM\ModelTrait;
  6.  
  7. /**
  8. * @Entity(tableClass="@forum_user")
  9. */
  10. class ForumUser
  11. {
  12.  
  13. use ModelTrait;
  14.  
  15. /** @Column(type="integer") @Id */
  16. public $id;
  17.  
  18. /** @Column */
  19. public $name = '';
  20.  
  21. /**
  22. * @ManyToMany(targetEntity="Topic", tableThrough="@forum_favorites", keyThroughFrom="forum_user_id", keyThroughTo="topic_id")
  23. */
  24. public $topics;
  25.  
  26. }

Example queries:

  1. // resolve many-to-many relation in query
  2.  
  3. // fetch favorite ropics for given user
  4. $user_id = 1;
  5. $user = ForumUser::query()->where('id = ?', [$user_id])->related('topics')->first();
  6.  
  7. foreach ($user->topics as $topic) {
  8. //
  9. }
  10.  
  11. // fetch users that have favorited a given topic
  12. $topic_id = 1;
  13. $topic = Topic::query()->where('id = ?', [$topic_id])->related('users')->first();
  14.  
  15. foreach ($topic->users as $user) {
  16. // ...
  17. }

ORM Queries

Fetch a model instance with a given id.

  1. $post = Post::find(23)

Fetch all instances of a model.

  1. $posts = Post::findAll();

With the above queries, relations will not be expanded to include related instances. In above example, the Post instance will not have its $comments property initialized.

  1. // related objects are not fetched by default
  2. $post->comments == null;

The reason for this is performance. By default, the required subqueries are not performed, which saves execution time. So if you need the related objects, you can use the related() method on the QueryBuilder to explicitly state which relations to resolve in this query.

So, to fetch a Post instance and include the associated Comment instances, you need to build a query which fetches the related objects.

  1. // fetch all, including related objects
  2. $posts = Post::query()->related('comments')->get();
  3. // fetch single instance, include related objects
  4. $id = 23;
  5. $post = Post::query()->related('comments')->where('id = ?', [$id])->first();

Note how the find(23) has been replaced with ->where('id = ?', [$id])->first(). This is because find() is a method defined on the Model. In the second example however, we have an instance of Pagekit\Database\ORM\QueryBuilder.

For more details on ORM queries and the regular queries, check out the documentation on database queries

Create new model instance

You can create and save a new model by calling the save() method on a fresh model instance.

  1. $user = new ForumUser();
  2. $user->name = "bruce";
  3. $user->save();

Alternatively you can call the create() method on the model class directly and provide an array of existing data to initialize the instance. Call save() afterwards to store the instance to the database.

  1. $user = ForumUser::create(["name" => "peter"]);
  2. $user->save();

Modify existing instance

Fetch an existing instance, perform any changes on the object and then call the save() method to store changes to the database.

  1. $user = ForumUser::find(2);
  2. $user->name = "david";
  3. $user->save();

Delete existing instance

Fetch an existing model instance and call the delete() method to remove this instance from the database.

  1. $user = ForumUser::find(2);
  2. $user->delete();