Models creation from scratch

Note

It is often preferable to design a database conceptually and then generate the models from the existing database.
The creation of models from scratch is only suitable for simple cases, and does not allow to skip a conceptualization phase.

Creating a model

Consider the following model representing a user:

../../_images/user-model.png

We will create it with devtools, in command prompt:

Ubiquity model user
../../_images/create-model.png

Note

A primary key is automatically added at creation as an auto-increment.
It is possible to change the default name of the primary key when launching the command :

Ubiquity model user -k=uid

Adding fields

Select the Add fields menu item:

  • Enter the field names separated by a comma:
../../_images/field-types.png

The added fields:

../../_images/fields-added.png

Generating the class

../../_images/generate-class.png

Below is the created model, without the accessors:

app/models/User.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace models;

use Ubiquity\attributes\items\Table;
use Ubiquity\attributes\items\Id;

#[Table('user')]
class User{

   #[Id]
   #[Column(name: "id",dbType: "int(11)")]
   #[Validator(type: "id",constraints: ["autoinc"=>true])]
   private $id;

   #[Column(name: "firstname",dbType: "varchar(30)")]
   #[Validator(type: "length",constraints: ["max"=>30,"notNull"=>false])]
   private $firstname;

   #[Column(name: "lastname",dbType: "varchar(45)")]
   #[Validator(type: "length",constraints: ["max"=>45,"notNull"=>false])]
   private $lastname;

   #[Column(name: "email",dbType: "varchar(150)")]
   #[Validator(type: "email",constraints: ["notNull"=>true])]
   #[Validator(type: "length",constraints: ["max"=>150])]
   private $email;
}
app/models/User.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace models;

/**
 * @table("name"=>"user")
 */
class User{
   /**
    * @id
    * @column("id","int(11)")
    * @validator("id",["autoinc"=>true])
    */
   private $id;

   /**
    * @column("firstname","varchar(30)")
    * @validator("length",["max"=>30,"notNull"=>false])
    */
   private $firstname;

   /**
    * @column("lastname","varchar(45)")
    * @validator("length",["max"=>45,"notNull"=>false])
    */
   private $lastname;

   /**
    * @column("firstname","varchar(150)")
    * @validator("email",["notNull"=>false])
    * @validator("length",["max"=>150])
    */
   private $email;
}

Modifying existing models

Ubiquity model

Without parameters, if some models exist, the model command suggests their loading:

../../_images/reload.png

The model to achieve is now the following:

../../_images/group_users.png

Select the Add/switch to model menu option, and enter group

../../_images/switch-to-group.png
Add:
  • primary key id in autoinc
  • the name field
  • The manyToMany relation with the User class :
../../_images/manytomany-users.png