Practice Working with Models in MVC in PHP
Suppose you have a table named page in your database
with some records. Let's create
a model Page with two methods. The first
method will retrieve one record by its id,
and the second method will retrieve an array of records
from a range of id:
<?php
namespace Project\Models;
use \Core\Model;
class Page extends Model
{
public function getById($id)
{
return $this->findOne("SELECT * FROM page WHERE id=$id");
}
public function getByRange($from, $to)
{
return $this->findMany("SELECT * FROM page WHERE id>=$from AND id<=$to");
}
}
?>
Now let's work with our model in the controller:
<?php
namespace Project\Controllers;
use \Core\Controller;
use \Project\Models\Page; // connect our model
class PageController extends Controller
{
public function test() {
$page = new Page; // create model object
$data = $page->getById(3); // get record with id=3
var_dump($data);
$data = $page->getById(5); // get record with id=5
var_dump($data);
$data = $page->getByRange(2, 5); // records with id from 2 to 5
var_dump($data);
}
}
?>
Create a table page in your database,
fill it with data. Test the code operation
described in the theory.