在我的项目中,数据库连接有效,因为我可以在db获取所有信息并且可以记录到db中。 Routs也在工作,当我在地址中输入一个单词“/ blog”时,但当我写“/ blog / 1”或其他一些数字时,它不起作用。
类“路由器”
<?php
class Router
{
private $routes;
public function __construct(){
$routesPath = ROOT.'/config/routes.php';
$this->routes = include($routesPath);
}
private function getURI(){
if (!empty($_SERVER['REQUEST_URI'])) {
return trim($_SERVER['REQUEST_URI'], '/');
}
}
public function run (){
$uri = $this->getURI();
foreach ($this->routes as $uriPattern=>$path) {
if (preg_match("~$uriPattern~", $uri)) {
$internalRoute = preg_replace("~$uriPattern~", $path, $uri);
$segments = explode('/', $internalRoute);
$controllerName = array_shift($segments).'Controller';
$controllerName = ucfirst($controllerName);
$actionName = 'action'.ucfirst(array_shift($segments));
$parameters = $segments;
$controllerFile = ROOT . '/controllers/' .
$controllerName . '.php';
if (file_exists($controllerFile)) {
include_once ($controllerFile);
}
$controllerObject = new $controllerName;
$result = call_user_func_array(array($controllerObject, $actionName), $parameters);
if ($result != null) {
break;
}
}
}
}
}
类BlogController
<?php
include_once ROOT. '/models/Blog.php';
class BlogController
{
public function actionIndex() {
$recordsList = array();
$recordsList = Blog::getRecordsList();
echo '<pre>';
print_r($recordsList);
echo '</pre>';
echo '<a href="#">Read more ></a>';
return true;
}
public function actionView($id){
if($id) {
$recordsItem = Blog::getRecordsItemById($id);
echo '<pre>';
print_r($recordsItem);
echo '</pre>';
}
echo '<a href="#">< Back </a>';
return true;
}
}
班级模特'博客'
<?php
class Blog
{
public static function getRecordsItemById($id){
$id = intval($id);
if ($id) {
$db = Database::getConnection();
$result = $db->query('SELECT * FROM `blog_records` WHERE `id` ='.$id);
$result->setFetchMode(PDO::FETCH_ASSOC);
$recordsItem = $result->fetch();
return $recordsItem;
return $result;
}
}
public static function getRecordsList() {
$db = Database::getConnection();
$recordsList=array();
$result = $db->query('SELECT * FROM `blog_records`'
. 'ORDER BY reg_date DESC');
$i = 0;
while ($row = $result->fetch()) {
$recordsList[$i] ['id'] = $row['id'];
$recordsList[$i] ['name'] = $row['name'];
$recordsList[$i] ['content'] = $row['content'];
$recordsList[$i] ['reg_date'] = $row['reg_date'];
$i++;
}
return $recordsList;
}
}