Config

7/8/2021

# Description

Như bài viết về singleton pattern, Config sử dụng Singleton pattern để có thể truy xuất về 1 instance duy nhất.

Kết hợp thêm DI container để có thể quản lí dependency này.

# Register DI container:

Singleton binding

$application->singleton(ConfigContract::class, Config::getInstance());
1

Vì Config đang extends Singleton nên không thể khởi tạo như bình thường như dùng operator new Class() mà phải thông qua method getInstance().

Sử dụng pakage Symfony Yaml để load toàn bộ config ở file app.yml khi khởi tạo application.

use Symfony\Component\Yaml\Yaml;

public function loadConfig()
{
    $configYml = Yaml::parseFile(APP_ROOT_DIR . '/Config/app.yaml');
    foreach ($configYml as $configKey => $configItem) {
        $this->set($configKey, $configItem);
    }
}
1
2
3
4
5
6
7
8
9

# Usage:

  1. Set giá trị config trong file config/app.yml

    foo: "bar"
    
    1
  2. Dùng Facade:

    use Nin\Libs\Facades\Config;
    
    Config::get('foo')
    // outout: "bar"
    
    1
    2
    3
    4
  3. Type hinting Nin\Libs\Config\Contract

    Vì Config đã được register ở DI Container nên có thể sử dụng bằng cách type hinting ở class bất kỳ

    use Nin\Libs\Config\Contract as ConfigContract;
    
    class FooController
    {
        protected ConfigContract $config;
    
        public function __construct(ConfigContract $config)
        {
            $this->config = $config;
        }
    
        public function indexAction()
        {
            $this->config->get('foo');
            // output: "bar"
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

Packagist: https://packagist.org/packages/nin/nin (opens new window)