1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| <?php
// pas besoin d'un singleton, cette simple fonction fera l'affaire !
function connection () {
static $pdo;
if (!isset($pdo)) {
if (!func_num_args()) throw new RuntimeException("Database link is not initialized");
list($dsn, $user, $pass, $options) = func_get_args() + array('', 'root', '', array());
$pdo = new PDO($dsn, $user, $pass, $options);
}
return $pdo;
}
function fetch_article_from_database ($id) {
$pdo = connection();
$pdo->prepare('SELECT * FROM `articles` WHERE `id`=:id');
if ($pdo->execute(array('id' => $id)))
return $pdo->fetch(PDO::FETCH_ASSOC);
return null;
}
function fetch_article_from_cache ($id) {
if (is_file($filename = dirname(__FILE__) . "/cache/article[$id].cache"))
return json_decode(file_get_contents($filename), true);
return false;
}
function get_article ($id) {
// si un cache existe, le renvoyer
if ($article = fetch_article_from_cache($id))
return $article;
// sinon, réccupérer les infos depuis la base
if (!$article = fetch_article_from_database($id))
return null;
// le mettre en cache
file_put_contents(dirname(__FILE__) . "/cache/article[$id].cache", json_encode($article));
return $article;
}
connection('mysql:dbname=testdb;host=127.0.0.1'); // initializer la connexion
// JOB //
// I pity the fool who doesn't sanitize user data !
if ($article_id = file_input(INPUT_GET, 'article', FILTER_SANITIZE_NUMBER_INT)) {
$article = get_article($article_id);
if (!$article)
header("HTTP/1.1 404 Not Found");
}
?>
<html>
<head>
<title><?=$article['title']?></title>
</head>
<body>
<? if (isset($article)): ?>
<article>
<header>
<h1><?=$article['title']?></h1>
<p><?=$article['subtitle']?></h1>
</header>
<? foreach (explode("\n\n", $article['body']) as $section): ?>
<section>
<?=$section?>
</section>
<? endforeach ?>
</article>
<? else: ?>
<h1>Non trouvé</h1>
<p>L'article recherché n'existe pas...</p>
<? endif ?>
</body>
</html> |
Partager