· 7 years ago · Sep 11, 2018, 05:30 PM
1.
2├── actions
3│  └── index.php
4├── data
5│  └── db.sq3
6├── dependencies
7│  ├── config.php
8│  └── dbQuery.php
9└── main.php
10
11<?php
12
13$action = 'index.php';
14require __DIR__ . '/actions/' . $action;
15
16function appController($action, $getArgs) {
17 static $getDependence;
18 if ($getDependence === null) {
19 $getDependence = initGetDependence(__DIR__ . '/dependencies');
20 }
21
22 $args = $getArgs($getDependence);
23 try {
24 $result = $action(...$args);
25 } catch(Throwable $err) {
26 throw new Exception('500');
27 }
28
29 return $result;
30}
31
32function initGetDependence($dir) {
33 $getDependence = function($name) use($dir, &$getDependence) {
34 $path = $dir . '/' . $name;
35 $dependence = require $path;
36
37 return $dependence($getDependence);
38 };
39
40 return $getDependence;
41}
42
43<?php
44
45extract(appController(function($dbQuery) {
46 list($rows) = $dbQuery('
47 select *
48 from `articles`
49 ');
50
51 return ['articles' => $rows];
52}, function($getDependence) {
53 return [
54 $getDependence('dbQuery.php'),
55 ];
56}));
57
58?>
59<div>
60 <?php foreach($articles as $article): ?>
61 <div>
62 <h2><?= htmlspecialchars($article['title']) ?></h2>
63 <div>
64 <?= $article['html'] ?>
65 </div>
66 </div>
67 <?php endforeach ?>
68</div>
69
70<?php
71
72return function($getDependence) {
73 $config = $getDependence('config.php');
74 $db = new PDO($config['db']);
75 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
76
77 // Ð´Ð»Ñ Ð¿Ñ€Ð¸Ð¼ÐµÑ€Ð°
78 $db->exec('drop table if exists `articles`');
79 $db->exec('
80 create table `articles` (
81 `id` integer not null primary key autoincrement,
82 `title` text,
83 `html` text
84 )
85 ');
86 $db->exec('delete from `articles`');
87 $db->exec('
88 insert into `articles` (`title`, `html`)
89 values
90 (
91 'Foo foo foo',
92 'test <a href="/foo">FOO</a>'
93 ),
94 (
95 'Bar bar bar',
96 'test <a href="/bar">BAR</a>'
97 )
98 ');
99
100 return function($sql) use($db) {
101 $st = $db->query($sql);
102
103 return [
104 $st->fetchAll(),
105 ];
106 };
107};
108
109<?php
110
111return function() {
112 return [
113 'db' => 'sqlite:' . realpath(__DIR__ . '/../data/db.sq3'),
114 ];
115};