在非 laravel 專案中使用 laravel 的特性 5: 配置 config && env

ZouZhipeng發表於2021-02-24

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 即可。

參考 致謝

  1. 非 Laravel 專案中整合使用 illuminate/config
  2. mattstauffer/Torch
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章