2017-10-04 56 views
3

我使用最簡單的示例創建了Slim 3和Twig項目。PHP內置服務器顯示索引頁而不是靜態文件

文件夾結構如下:

- public 
    - index.php 
    - style.css 
index.php

應用程序代碼如下:

<?php 
require 'vendor/autoload.php'; 

$app = new \Slim\App(); 
$container = $app->getContainer(); 

// Twig 
$container['view'] = function ($container) { 
    $view = new \Slim\Views\Twig('src/views', [ 
    'cache' => false // TODO 
    ]); 

    // Instantiate and add Slim specific extension 
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/'); 
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath)); 

    return $view; 
}; 

$app->get('/', function ($request, $response, $args) { 
    return $this->view->render($response, 'index/index.html.twig'); 
})->setName('index'); 

$app->run(); 

現在的問題是,試圖加載/style.css顯示主要的頁面,而不是(index/index.html.twig) 。爲什麼我不能訪問style.css文件?

我用它的PHP服務器內置的開發服務器,使用命令:

php -S localhost:8000 -t public public/index.php

我如何可以加載資產?這裏有什麼問題?

回答

3

原因是PHP內置的開發服務器是'啞'。

我必須在index.php文件中包含此檢查作爲第一件事。

// To help the built-in PHP dev server, check if the request was actually for 
// something which should probably be served as a static file 
if (PHP_SAPI == 'cli-server') { 
    $url = parse_url($_SERVER['REQUEST_URI']); 
    $file = __DIR__ . $url['path']; 
    if (is_file($file)) return false; 
} 

來源:https://github.com/slimphp/Slim-Skeleton/blob/master/public/index.php

相關問題