简体   繁体   English

在 Slim 框架中设置 File.env

[英]Setup File .env in Slim Framework

I'm new to slim framework.我是苗条框架的新手。 I'd try to add.env file in root folder project and then I want to access the value inside.env file.我会尝试在根文件夹项目中添加 .env 文件,然后我想访问 .env 文件中的值。 I've tried use this package https://github.com/vlucas/phpdotenv and load.env in index.php.我试过在 index.php 中使用这个 package https://github.com/vlucas/phpdotenv和 load.env。 But when I tried to get the value in.env file use like ex: getenv("DB_NAME") it returns false.但是,当我尝试获取 in.env 文件中的值时,请使用 ex: getenv("DB_NAME") 它返回 false。 Not return string value of DB_NAME.不返回 DB_NAME 的字符串值。

.env .env

DB_HOST = localhost
DB_PORT = 3306
DB_NAME = DB
DB_USER = root
DB_PASSWORD = 

index.php index.php

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

I use slim framework ^4.*, web server laravel valet, database MySQL.我使用苗条框架^4.*,web服务器laravel代客,数据库MySQL。 Or is there any other alternative way to configure.env in slim framework?或者还有其他替代方法可以在苗条框架中配置.env 吗? Thank You.谢谢你。

From package readme file :来自package 自述文件

Using getenv() and putenv() is strongly discouraged due to the fact that these functions are not thread safe, however it is still possible to instruct PHP dotenv to use these functions.强烈建议不要使用 getenv() 和 putenv(),因为这些函数不是线程安全的,但是仍然可以指示 PHP dotenv 使用这些函数。 Instead of calling Dotenv::createImmutable , one can call Dotenv::createUnsafeImmutable , which will add the PutenvAdapter behind the scenes.可以调用Dotenv::createUnsafeImmutable而不是调用Dotenv::createImmutable这将在幕后添加 PutenvAdapter。 Your environment variables will now be available using the getenv method, as well as the super-globals.您的环境变量现在可以使用 getenv 方法以及超级全局变量获得。

So the main method of getting these values is using $_ENV and $_SERVER super-global not getenv() function.所以获取这些值的主要方法是使用$_ENV$_SERVER super-global not getenv() function。

You should either try to retrieve the values like:您应该尝试检索以下值:

$db_name = $_ENV['DB_NAME'];

or load the.env file like the example provided in the package:或像 package 中提供的示例一样加载 .env 文件:

$dotenv = Dotenv\Dotenv::createUnsafeImmutable(__DIR__);
$dotenv->load();

Also, make sure you pass correct directory (the one that.env file resides in) as the parameter.此外,请确保您将正确的目录(即.env 文件所在的目录)作为参数传递。 That normally should not be in the same directory as index.php but the example code you provide implies you are putting both files in one directory.这通常不应与index.php位于同一目录中,但您提供的示例代码暗示您将两个文件放在一个目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM