2012-09-08 127 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

謝謝,工作的魅力:) –