当我单击index.php上指向users.php页面的链接时,我得到的数据与index.php上的数据相同,并且应该有所不同。我到users.php的链接路线很好,我认为问题出在核心控制器(Core.php)中,我似乎找不到问题。控制器名称也是UserController,当我将users.php的名称更改为usercontroller.php并将href更改为usercontroller时,它也可以正常工作。这是我的代码:
代码结构:
Project
|
+-- App
| |
| +-- Controllers
| |
| +-- PageController.php
| +-- UserController.php
| +-- Libraries
| |
| +-- Core.php
| +-- Controller.php
| +-- Views
| |
| +-- pages
| |
| +-- users.php
| +-- index.php
index.php:
<?php require '../App/Views/includes/header.php' ; ?>
<h1>Homepage!!!</h1>
<a href="users">Users</a>
<?php require '../App/Views/includes/footer.php' ; ?>
PageController.php
<?php
namespace App\Controllers;
use App\Libraries\Controller;
class PageController extends Controller
{
public function index()
{
$this->view('pages/index');
}
}
UserController.php:
<?php
namespace App\Controllers;
use App\Libraries\Controller;
class UserController extends Controller
{
public function index()
{
$this->view('pages/users');
}
}
Controller.php:
<?php
namespace App\Libraries;
class Controller
{
public function model($model)
{
require_once '../App/Models/' . $model . '.php';
return new $model();
}
public function view($view, $data = [])
{
if (file_exists('../App/Views/' . $view . '.php')) {
require_once '../App/Views/' . $view . '.php';
} else {
die("View does not exist!!!");
}
}
}
Core.php
<?php
namespace App\Libraries;
class Core
{
protected $currentController = 'App\Controllers\PageController';
protected $currentMethod = 'index';
protected $params = [];
public function __construct()
{
$url = $this->getUrl();
if (file_exists('../App/Controllers/' . ucwords($url[0]). '.php')) {
$this->currentController = ucwords($url[0]);
if (isset($url[0])) {
$this->currentController = '\App\Controllers\\' . ucwords($url[0]);
}
unset($url[0]);
}
$this->currentController = new $this->currentController;
if (isset($url[1])) {
if (method_exists($this->currentController, $url[1])) {
$this->currentMethod = $url[1];
unset($url[1]);
}
}
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl()
{
if (isset($_GET['url'])) {
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
}
答案 0 :(得分:0)
这是因为现在您正在搜索名为Users
的控制器。您应该将控制器名称和文件名从UserController
更改为Users
,或者可以将其添加到Core类中:
public function __construct()
{
$url = $this->getUrl();
if (file_exists('../App/Controllers/' . ucwords($url[0]). 'Controller.php')) {
$this->currentController = ucwords($url[0]);
if (isset($url[0])) {
$this->currentController = '\App\Controllers\\' . ucwords($url[0]).'Controller';
...
}
现在,如果您有例如/ users的网址,则应将控制器命名为UsersController