使用 Laravel 框架包含 PHP 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17159046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Including PHP files with Laravel framework
提问by user1072337
I am trying to "include" a php script into one of my views (landing.blade.php).
我正在尝试将 php 脚本“包含”到我的一个视图 (landing.blade.php) 中。
The script is in:
脚本在:
/laravel-master/public/assets/scripts/config.php
When I try to include this code in the view:
当我尝试在视图中包含此代码时:
<?php include_once('/assets/scripts/config.php'); ?>
I get the error: include_once(/assets/scripts/config.php): failed to open stream: No such file or directory
我收到错误: include_once(/assets/scripts/config.php): failed to open stream: No such file or directory
This is on localhost using MAMP. I'm not sure if there is a different set of rules I need to use with Laravel 4 to include a php file. Thank you for your help!
这是在本地主机上使用 MAMP。我不确定在 Laravel 4 中是否需要使用一组不同的规则来包含 php 文件。感谢您的帮助!
回答by rmobis
First, it's not really recommended that you keep your PHP files in the public
directory, they should be kept inside the app
folder. I'd suggest you create a folder inside app
, something like includes
and put your files there. Then, you include it, do:
首先,不建议您将 PHP 文件保存在public
目录中,它们应该保存在app
文件夹中。我建议你在里面创建一个文件夹app
,比如includes
把你的文件放在那里。然后,你包括它,做:
include(app_path().'/includes/config.php');
Although, since it looks like you're trying to load some configuration files, I'd recommend you also check out Laravel's own way of handling configurations. For instance, if you created a myapp.php
file inside the app/config
folder, Laravel would handle it automatically for you, as long as you'd have some key-value pairs, like this:
虽然,由于看起来您正在尝试加载一些配置文件,我建议您还查看 Laravel 自己的配置处理方式。例如,如果你在myapp.php
文件app/config
夹中创建了一个文件,Laravel 会自动为你处理它,只要你有一些键值对,就像这样:
<?php
return [
'name' => 'Raphael',
'gorgeous' => true
];
You could then retrieve these values using the Config
class:
然后,您可以使用Config
该类检索这些值:
Config::get('myapp.name'); // Raphael
This is a better solution because you can also take advantage of Laravel's environment configuration.
这是一个更好的解决方案,因为您还可以利用 Laravel 的环境配置。