在非 laravel 项目中使用 laravel 的特性 5: 配置 config && env
env config
config
composer 安装所需的包
composer require illuminate/config 新建配置文件 config/app.php
<?php return [ 'app' => [ 'env' => 'dev', ], ]; 项目入口文件 index/env.php
<?php use Illuminate\Config\Repository; require_once __DIR__ . '/../vendor/autoload.php'; $configPath = __DIR__ . '/../config/'; // Init $config = new Repository(require $configPath . 'app.php'); // Get config using the get method mm($config->get('app.env')); // Get config using ArrayAccess mm($config['app.env']); // Set a config $config->set('settings.greeting', 'Hello there how are you?'); dd($config->get('settings.greeting')); 命令行开启服务 php -S localhost:8000 并访问 http://localhost:8000/index/env.php 即可。
dotEnv
composer 安装 env 所需的包
composer require vlucas/phpdotenv 创建 .env 文件 (同时需要创建 .env.example)
ENV=local 修改配置文件 config/app.php
<?php return [ 'env' => $_ENV['ENV'] ?? 'dev', 'name' => $_ENV['APP_NAME'] ?? 'non-laravel', ]; 新建一个文件 src/Config.php,加载上述配置文件
<?php namespace App; use Illuminate\Config\Repository; use Illuminate\Filesystem\Filesystem; class Config extends Repository { public function loadConfigFiles($path) { $fileSystem = new Filesystem(); if (!$fileSystem->isDirectory($path)) { return; } foreach ($fileSystem->allFiles($path) as $file) { $relativePathname = $file->getRelativePathname(); $pathInfo = pathinfo($relativePathname); if ($pathInfo['dirname'] == '.') { $key = $pathInfo['filename']; } else { $key = str_replace('/', '.', $pathInfo['dirname']) . '.' . $pathInfo['filename']; } $this->set($key, require $path . '/' . $relativePathname); } } } 新建一个项目主文件 src/Application.php
<?php namespace App; use Dotenv\Dotenv; use Illuminate\Filesystem\Filesystem; class Application { public Config $config; public Filesystem $fileSystem; public string $environment; /** * Application constructor. */ public function __construct() { $this->config = new Config(); $this->fileSystem = new Filesystem(); $this->environment = $this->getEnvironment(); $this->config->loadConfigFiles(__DIR__ . '/../config'); } /** * @return string */ public function getEnvironment(): string { $environment = ''; $environmentPath = __DIR__ . '/../.env'; if ($this->fileSystem->isFile($environmentPath)) { $dotenv = Dotenv::createImmutable(dirname(__DIR__)); $dotenv->load(); } return $environment; } } 单一入口文件 index/env.php
<?php use App\Application; require_once __DIR__ . '/../vendor/autoload.php'; $app = new Application(); mm($app->config->get('app.env')); dd($app->config->get('app.name')); 命令行开启服务 php -S localhost:8000 并访问 http://localhost:8000/index/env.php 即可。
参考 致谢
本作品采用《CC 协议》,转载必须注明作者和本文链接
关于 LearnKu