Models



Models are often the most complex part of the MVC architecture. It is the section where the code density is highest and where data is stored to be sent to views. Both PHP codes and Database commands are designed on these structures. Usually, the most common mistake users make is giving the controller the responsibility that a model should take. A controller should only be a section containing simple codes such as directing the process according to user input. Apart from these, all codical operations are included in the model.

Model files are created in the Models/ directory.

 

 

# Section Headings


# Creating the Model File

# Including Model in Controller

# internal Model Design
# Grand Model Extension

 

 

# Creating the Model File


You can create a sample model file as follows.

File: Projects/Frontend/Models/UsersModel.php
<?php 
class UsersModel extends Model
{
    public static function rowId(int $id)
    {
         return DB::whereId($id)->users()->row();
    }
}
Including Model in Controller

All you have to do is call your model in the controller. If the model and the controller name are the same, you must use your model class with a pseudonym in the controller. This situation is already a rule of Object Oriented Programming.

File: Projects/Frontend/Controllers/Users.php
<?php namespace Project\Controllers;

use UsersModel;

class Users extends Controller
{
    public function main()
    {
         output( UsersModel::rowId(5) );
    }
}

 

 

# Internal Model Design


To access your non-static models static, define the class name by adding the internal prefix. Class designs are applied dynamically, as static definitions restrict some uses. Despite this dynamic structure, it is possible to access methods statically thanks to this prefix.

<?php
class InternalUsersModel extends Model
{
    public function rowId(int $id)
    {
        return DB::whereId($id)->users()->row();
    }
}

After the definition above, you can use the model file as follows.

File: Projects/Frontend/Controllers/Users.php
<?php namespace Project\Controllers;

use UsersModel;

class Users extends Controller
{
    public function main()
    {
         output( UsersModel::rowId(5) );
    }
}

 

 

# Grand Model Extension


The Grand Model extension is designed to make database methods more useful and practical. Click for the continuation of the subject. Still, to give an example, this extension does not require the definitions we made for rowId() above.

<?php
class InternalUsersGrand extends GrandModel
{
    
}

After the definition above, you can use the model file as follows.

output( UsersGrand::rowId(1) );