LoginSignup
1
2

More than 5 years have passed since last update.

お手軽簡単PHPで設定ファイルローダを作ってみた

Last updated at Posted at 2017-06-23

はじめに

  • 前回に続いて、勢いで設定ファイルローダを作ってみました。

ソースコード

<?php

namespace XXXX;

/**
 * コンフィグの基底クラスです
 */
class Config
{

    /**
     * @var string $directory 対象のディレクトリ
     */
    protected static $directory;

    /**
     * 対象のディレクトリを設定します
     *
     * @param string $directory ディレクトリ
     */
    public static function setConfigDirectory($directory)
    {
        self::$directory = $directory;
    }

    /**
     * 対象のディレクトリを返却します
     *
     * @return string ディレクトリ
     */
    public static function getConfigDirectory()
    {
        return rtrim(self::$directory, '/\\');
    }

    /**
     * 設定ファイル情報を返却します
     *
     * @param string $route ファイルルート
     * @return array $config[$key] 設定情報
     */
    public static function get($route)
    {
        $values = preg_split('/\./', $route, -1, PREG_SPLIT_NO_EMPTY);
 
        $key = array_pop($values);
        $file = array_pop($values) . '.php';
 
        $path = self::getConfigDirectory() . DIRECTORY_SEPARATOR . $file;
 
        $config = include($path);

        return $config[$key];
    }
}

使い方

設定ファイルの読み込み

Config::setConfigDirectory(ROOT_DIR . '/config');

設定ファイルの取得

app.php
return array(
    'search_url' => array(
        'pc' => 'http://hogehoge.com/',
        'sp' => 'http://mobile.hogehoge.com/'
    ),
);
Config::get('app.search_url');

全ページリンク

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2