MVC pielietojums PHP
Aplūkosim visu apgūstā materiāla kopīgu pielietojumu. Pieņemsim, ka mūsu vietnē ir dažas rakstu lapas. Mēs vēlamies vai nu rādīt vienu rakstu, vai rādīt visus rakstus. Apskatīsim, kā to izdarīt mūsu ietvarā.
Tabulā datu bāzē
Sākumā izveidosim tabulu pages
datu bāzē. Pievienosim tajā kolonnas id,
title un text. Aizpildīsim šo
tabulu ar kādiem datiem
caur PhpMyAdmin.
Modelis
Izveidosim modeli ar metodi viena ieraksta iegūšanai un metodi visu ierakstu iegūšanai:
<?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");
}
}
?>
Maršrutizācija
Izveidosim atbilstošu maršrutizāciju:
<?php
use \Core\Route;
return [
new Route('/page/:id', 'page', 'one'),
new Route('/pages/', 'page', 'all'),
];
?>
Kontrolieris
Izveidosim kontrolieri:
<?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 = 'Visu lapu saraksts';
$pages = (new Page) -> getAll();
return $this->render('page/all', [
'pages' => $pages,
'h1' => $this->title
]);
}
}
?>
Skati
Izveidosim skatu metodei one:
<h1><?= $h1; ?></h1>
<div id="content">
<?= $text; ?>
</div>
Izveidosim skatu metodei all:
<h1><?= $h1; ?></h1>
<div id="content">
<table>
<tr>
<th>id</th>
<th>title</th>
<th>saite</th>
</tr>
<?php foreach ($pages as $page): ?>
<tr>
<td><?= $page['id']; ?></td>
<td><?= $page['title']; ?></td>
<td><a href="/page/<?= $page['id']; ?>/">saite uz lapu</td>
</tr>
<?php endforeach; ?>
</table>
</div>
Praktiskie uzdevumi
Pieņemsim, ka jūsu datu bāzē ir produkti.
Katrs produkts satur nosaukumu, cenu un
daudzumu, aprakstu. Realizējiet viena
produkta attēlošanu pēc id un visu produktu attēlošanu līdzīgi
kā tas darīts teorijā.