Models
With the database tables created, the next step is to create the model classes. Within terminal, run the opus model CLI command:
apex opus model Disaster/Models/Location --dbtable disaster_locations --magic
apex opus model Disaster/Models/Volunteer --dbtable disaster_volunteers --magic
With the first command you will be prompted to create the parent directory, and asked whether or not you would like to create a model for the foreign key relationships found. Simply hit Enter to accept the default value of all questions, and upon completion you will notice a new directory at /src/Disaster/Models/ which scontains four files, one for each database table created.
Anatomy of a Model
As explained within the models section of the documentation, Apex models heavily utilize constructor property promotion. For example, if yu look at the /src/Disaster/Models/Location.php file that was generated, you will see the __construct()
method as:
[data-line=10]
public function __construct(
protected int $id,
protected bool $is_active = true,
protected string $country = '',
protected string $city = '',
protected string $notes = '',
protected ?DateTime $created_at = null,
protected ?DateTime $updated_at = null
) {
upon creating a model via the opus model CLI command it will take into accont all attributes of the database table including columns, data types, default values, nullables, forien key constraints, et al.
With the --magic
flag present, all properties can be directly accessed, so in the case of the above model:
echo "City is " . $obj->city;
$obj->city = 'Toronto';
$obj->save();
If you dislike being able to access the properties directly and instead prefer the standard getter / setter methods, simply omit the --magic
flag from the above commands and the models will be generated as such with get / set methods for each property.