What Are They? Models in are designed to access and work with information in your database. For example you could have a model that has functions for CRUD ( create, read, update and delete) hotel reservations or whatever you need from your database. Models can also be used for purposes other than only database use.
Salem not require you to use models in your application, but it is highly recommended, even more if you are trying to implement MVC architecture.
My First Model Create a new PHP file at “application/models/abstract.php”, this will be our model with a basic structure. Let's say we want our model to be a bit generic for make queries to our database , so let's add a function to query a table, filtering for a specific field and a condition to fulfill.
abstracto.php
<?php use Salem\db; // I assume that we have already configured the db section class abstracto { //A simple function public function makeQuery($table, $field, $operation, $value) { // Return results from a query return db::db($table)->select('*')->where($field,$operation,$value)->execute(); } } ?>
Use It Now to load your model and use it you will do this in a controller:
maincontroller.php
<?php namespace Controller; use Salem\load, Salem\View; class Main { public function searchDescription() { $table = load::model('abstract'); #Think the db have a table called house with a field named description, where we will search for a word inside it $val="pool"; $fields = $table-> makeQuery("house", "description","like", '%' . $val . '%'); //The next step will be to render a view whit this data } } ?>
Parent Models It is also possible to make model classes extend from other model classes. For example using the last abstracto model we can extend it for use it in several models or at least in this one to make things easier: Create a PHP file in this path: application/models/newFolder/house.php
house.php
<?php use Salem\load; load::parentModel('abstracto'); class house extends abstracto { public function containDescription($val) { // Return results from a query return self::makeQuery("house", "description","like", '%' . $val . '%'); } } ?>
maincontroller.php
<?php namespace Controller; use Salem\load, Salem\View; class Main { public function searchDescription() { $table = load::model('house'); $val="pool"; $fields = $table->containDescription($val); //The next step will be to render a view whit this data } } ?>