GeniXCMS

Model Class

categoryAPI edit_calendar31 Mar 2026

Model Class (ORM / ActiveRecord)


The Model class provides a robust, ActiveRecord-style ORM for interacting with your database. It allows you to treat database rows as native PHP objects, inheriting complex data manipulation capabilities like finding, saving, updating, and deleting with minimal boilerplate code.


🏗️ Creating Your Model

To create a domain entity, simply extend the Model class and define your target table name.

/**
 * Example: Custom Book Model
 */
class Books extends Model 
{
    protected $table = 'books';
    protected $primaryKey = 'id'; // Default is 'id'
}

🔍 Finding & Retrieving Records

The Model class features a fluent interface for data retrieval.

Model::find(int $id)

Quickly retrieve a single record by its primary key. Returns a model instance or null.

$book = Books::find(12);
if ($book) {
    echo $book->title;
}

Model::all()

Returns a collection (array of objects) containing all records from the table.


💾 Saving & Updating Data

The save() method intelligently determines whether to execute an INSERT or an UPDATE based on the existence of the primary key.

Creating New Records

// Instantiate and set properties
$book = new Books();
$book->title = "The Art of CMS";
$book->author = "GeniXCMS Team";
$book->save(); // Performs INSERT

// Or use the static shorthand
Books::create([
    'title' => 'Fast Lane',
    'status' => '1'
]);

Updating Existing Records

$book = Books::find(12);
$book->title = "Updated Title";
$book->save(); // Performs UPDATE

⚡ Chainable Query Integration

Models integrate natively with the Query Builder, allowing you to start complex queries directly from your class.

// Find specific records using chaining
$active_books = Books::where('status', '1')
    ->orderBy('date', 'desc')
    ->limit(10)
    ->get();

📝 Technical Method Summary

Method Role Return Type
all() Retrieve all table records. array<objects>
find($id) Look up a single record by its PK. Model \| null
where() Initiate a fluent query condition. QueryBuilder
create($data) Static shorthand for immediate insertion. bool
save() Persistent save (Insert/Update) of the current object. bool
delete() Permanent removal of the current object. bool

🔮 Dynamic Attributes

GeniXCMS uses PHP Magic Methods (__get and __set) to map database columns to object properties. This ensures your code remains clean and intuitive.

$post = Posts::find(42);
echo $post->content; // Automatically resolves to the 'content' column

priority_high
ImportantData Integrity: When using Model::save(), ensure your table's primary key is correctly defined in the $primaryKey property if it deviates from the standard id. Failure to do so may result in duplicate records.

See Also

  • Query Builder — Mastering complex SQL queries through the model layer.
  • Db Class — Direct database interaction for non-model logic.