需要字符串时如何正确包含文件?

How to properly include a file when a string is needed?

我有一个本地文件需要包含在开始的 Silex 应用程序中。我刚开始,我有所有的样板代码设置 - 特别是这里。

// I need to return test.php for this route
$app = new Silex\Application();
$app->get('/', function() use($app) {
    return $string;  // put the file in a string
});
$app->run();

经过一番谷歌搜索后,我找到了这些文章:SO, PHP.net

所以看起来我可以使用 file_get_contents(),如果我需要评估代码,我可以将它包装在 eval() 中。或者我可以使用 link.

中显示的其他方法

我希望只使用类似于 require() 的东西,但 Silex 需要返回一个字符串。我想我可以编写自己的辅助函数 parseFile() 但这必须在其他地方完成了吗?

更新

// this does not work, I'v verified the path is correct.
return file_get_contents($path, TRUE);

也许是这个?

ob_start();
require 'somefile.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;

文档有点难以浏览,但这里有适当的锚点 -

Sensio Labs Documentation

正如您所建议的,有更直接的方法。

您基本上需要使用恰当命名的 sendFile() 方法。

$app->get('/files/{path}', function ($path) use ($app) {
    if (!file_exists('/base/path/' . $path)) {
        $app->abort(404);
    }

    return $app->sendFile('/base/path/' . $path);
});