Applying MVC in PHP
Let's look at the joint application of everything we have learned. Suppose, for example, we have some article-pages on our site. We want to either show one article or show all articles. Let's consider how to do this in our framework.
Table in the Database
First, let's create a table pages
in the database. Let's add columns id,
title and text. Let's fill this
table with some data
via PhpMyAdmin.
Model
Let's create a model with a method to get one record and a method to get all records:
<?php
namespace Project\Models;
use \Core\Model;
class Page extends Model
{
public function getById($id)
{
return $this->findOne("SELECT * FROM pages WHERE id=$id");
}
public function getAll()
{
return $this->findMany("SELECT id, title FROM pages");
}
}
?>
Routing
Let's create the appropriate routing:
<?php
use \Core\Route;
return [
new Route('/page/:id', 'page', 'one'),
new Route('/pages/', 'page', 'all'),
];
?>
Controller
Let's create a controller:
<?php
namespace Project\Controllers;
use \Core\Controller;
use \Project\Models\Page;
class PageController extends Controller
{
public function one($params)
{
$page = (new Page) -> getById($params['id']);
$this->title = $page['title'];
return $this->render('page/one', [
'text' => $page['text'],
'h1' => $this->title
]);
}
public function all()
{
$this->title = 'List of all pages';
$pages = (new Page) -> getAll();
return $this->render('page/all', [
'pages' => $pages,
'h1' => $this->title
]);
}
}
?>
Views
Let's create a view for the one method:
<h1><?= $h1; ?></h1>
<div id="content">
<?= $text; ?>
</div>
Let's create a view for the all method:
<h1><?= $h1; ?></h1>
<div id="content">
<table>
<tr>
<th>id</th>
<th>title</th>
<th>link</th>
</tr>
<?php foreach ($pages as $page): ?>
<tr>
<td><?= $page['id']; ?></td>
<td><?= $page['title']; ?></td>
<td><a href="/page/<?= $page['id']; ?>/">link to page</td>
</tr>
<?php endforeach; ?>
</table>
</div>
Practical Tasks
Suppose you have products in your database.
Each product contains a name, price,
quantity, and description. Implement the display of one
product by id and all products similar to
how it is done in the theory.