MVC

Najprostsza implementacja Model – View – Controler musi składać się z 3 plików [28]:

Model:

<?php

function modelPobierz($nazwa_pliku=__DIR__.'/books.json') {
  if ( file_exists($nazwa_pliku) )  {
    $_books = json_decode(file_get_contents($nazwa_pliku), true);
  }
  return $_books;
}

function modelNowa(&$books, 
                   $title, $authors, 
                   $nazwa_pliku=__DIR__.'/books.json') {
  $books[] = 
        [ 'title' => $title,
          'authors' => $authors
        ];
  return file_put_contents( $nazwa_pliku, json_encode($books) );
}

Widok:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Książki</title>
<style> td {padding: 10px; border:1px solid gray;} </style>
</head>
<body>
<?php
if (count($books)>0) {
?>    
    <table>
    <?php foreach ($books as $book): ?>
    <tr><td><?= $book['title'] ?></td><td><?= $book['authors'] ?></td></tr>
    <?php endforeach ?>
    </table>
<?php
}
?>
<form action="ex28c.php" method="get"> 
<!-- metoda get lub post; get - w adresie URL wartości -->
<h3>Nowa książka</h3>
<div>Autorzy:<input type="text" name="authors" /></div>
<div>Tytuł:<input type="text" name="title" /></div>
<input type="submit" value="Zapisz"/>
</form>
</body>
</html>

Kontroler:

<?php
// Prosta implementacja MVC = model / widok / kontroler
include "ex28m.php"; // model

$books = modelPobierz();
// $books widoczna w widoku
// http://php.net/manual/pl/language.variables.scope.php

// poniżej kontroler (główny moduł)
$nowa = isset($_GET['title']) || isset($_GET['authors']);
if ($nowa) {
  modelNowa($books, $_GET['title'], $_GET['authors']);
}
include "ex28v.php"; // widok

Wywołanie

<?php
include 'ex28c.php';