2012-09-08 132 views
1

我正在尝试为我的项目编写自己的小MVC框架,我可以直接放入并快速启动,主要用于学习目的。每个请求将通过index.php路由具有此代码:PHP file_exists返回false

<?php 

// Run application 
require 'application/app.php'; 
$app = new App(); 
$app->run(); 

这是我的应用程序类:

<?php 

class App { 

    public function run() { 
     // Determine request path 
     $path = $_SERVER['REQUEST_URI']; 

     // Load routes 
     require_once 'routes.php'; 

     // Match this request to a route 
     if(isset(Routes::$routes[$path])) { 

     } else { 
      // Use default route 
      $controller = Routes::$routes['/'][0]; 
      $action = Routes::$routes['/'][1]; 
     } 

     // Check if controller exists 
     if(file_exists('controllers/' . $controller . '.php')) { 
      // Include and instantiate controller 
      require_once 'controllers/' . $controller . '.php'; 
      $controller = new $controller . 'Controller'; 

      // Run method for this route 
      if(method_exists($controller, $action)) { 
       return $controller->$action(); 
      } else { 
       die('Method ' . $action . ' missing in controller ' . $controller); 
      } 
     } else { 
      die('Controller ' . $controller . 'Controller missing'); 
     } 
    } 

} 

,这是我的路线文件:

<?php 

class Routes { 

    public static $routes = array(
     '/' => array('Pages', 'home') 
    ); 

} 

当我尝试加载根目录(/)我得到这个:

控制器PagesController失踪

出于某种原因,file_exists功能不能看到我的控制器。这是我的目录结构:

/application 
    /controllers 
     Pages.php 
    /models 
    /views 
    app.php 
    routes.php 

因此,通过使用if(file_exists('controllers/' . $controller . '.php'))app.php,它应该能够找到controllers/Pages.php,但它不能。

任何人都知道我可以解决这个问题吗?

回答

2

您正在为您的包含使用相对路径。随着应用程序的增长,它将成为一场噩梦。

我建议你

  • 写一个自动加载类,与包括文件的交易。使用一些映射机制将名称空间/类名转换为路径。
  • 使用绝对路径。请参阅下面的调整代码。

例子:

// Run application 
define('ROOT', dirname(__FILE__)); 
require ROOT . '/application/app.php'; 
$app = new App(); 
$app->run(); 

及更高版本:

// Check if controller exists 
if(file_exists(ROOT . '/application/controllers/' . $controller . '.php')) { 
    // Include and instantiate controller 
    require_once ROOT. '/application/controllers/' . $controller . '.php'; 
    $controller = new $controller . 'Controller'; 
+0

谢谢,工作的魅力:) –