spl_autoload_register似乎没有注册该类

时间:2017-11-03 17:37:33

标签: php nginx php-7

我正在研究一个简单的MVC,它适用于localhost但不适用于生产服务器。

错误:

Fatal error: Uncaught Error: Class 'Route' not found in /var/www/html/inc/route.php:3 Stack trace: #0 /var/www/html/index.php(3): require_once() #1 {main} thrown in /var/www/html/inc/route.php on line 3

Nginx重写规则:

location / {
    rewrite ^/(.*)$ /index.php?return=$1 last;
}

的index.php

<?php
 require_once "./inc/autoload.php";
 require_once "./inc/route.php";
?>

autoload.php

<?php
spl_autoload_register(function($includeName) {

 if(file_exists(__DIR__ . '/../class/'.$includeName.'.class.php')) {
  $pathClass = strtolower(__DIR__ .'/../class/'.$includeName.'.class.php');
  require_once($pathClass);
 }

});

spl_autoload_register(function($includeName) {

  if(file_exists(__DIR__ . '/../controllers/'.$includeName.'.php')) {
   $pathController = strtolower(__DIR__ .'/../controllers/'.$includeName.'.php');
   require_once($pathController);
 }

});
?>

这只会让我感到困惑。

编辑:添加/class/route.class.php和/inc/route.php

route.class.php

<?php
  class Route {
    public static $validRoutes = array();
    public static function set($route, $function) {
    public statis $url = $_GET['return'];
    if(empty(self::$url) == 1) {
    public static $url = "index"
    }
      self::$validRoutes[] = $route;
      if($url == $route) {
        $function->__invoke();
      } else {
        echo "Route not found";
      }
    }
  }
 ?>

route.php

<?php

  Route::set('index.php', function() {
    echo "Home";
  })

 ?>

2 个答案:

答案 0 :(得分:3)

你看file_exists(__DIR__ . '/../class/'.$includeName.'.php') - Route.php,然后使用strtolower()并尝试包含route.php

答案 1 :(得分:0)

您正在寻找class/Route.class.php而不是class/route.class.php等文件。

你可以使用这个完全相同的自动加载(没有错误)并且看起来更干净:

<?php

spl_autoload_register(function($className) {

  // Get parent directory and filename
  $baseDir = dirname(__DIR__);
  $fileName = strtolower($className) . '.class.php';

  // List directories to search for class
  $dirs = [
    $baseDir . '/class',
    $baseDir . '/controllers',
  ];

  // Search a class in every directory
  foreach ($dirs as $dir) {
    if (file_exists($dir . '/' . $filename)) {
        // Class file exists, include and return
        include($dir . '/' . $filename);
        return;
    }
  } 
});