Creating a config file in PHP

前端 未结 10 2110
难免孤独
难免孤独 2020-11-27 10:36

I want to create a config file for my PHP project, but I\'m not sure what the best way to do this is.

I have 3 ideas so far.

1-Use Variable<

相关标签:
10条回答
  • 2020-11-27 10:48

    I normally end up creating a single conn.php file that has my database connections. Then i include that file in all files that require database queries.

    0 讨论(0)
  • 2020-11-27 10:56

    Define will make the constant available everywhere in your class without needing to use global, while the variable requires global in the class, I would use DEFINE. but again, if the db params should change during program execution you might want to stick with variable.

    0 讨论(0)
  • 2020-11-27 10:57

    Here is my way.

    <?php
    
    define('DEBUG',0);
    
    define('PRODUCTION',1);
    
    
    
    #development_mode : DEBUG / PRODUCTION
    
    $development_mode = PRODUCTION;
    
    
    
    #Website root path for links
    
    $app_path = 'http://192.168.0.234/dealer/';
    
    
    
    #User interface files path
    
    $ui_path = 'ui/';
    
    #Image gallery path
    
    $gallery_path = 'ui/gallery/';
    
    
    $mysqlserver = "localhost";
    $mysqluser = "root";
    $mysqlpass = "";
    $mysqldb = "dealer_plus";
    

    ?>

    Any doubts please comment

    0 讨论(0)
  • 2020-11-27 10:59

    I use a slight evolution of @hugo_leonardo 's solution:

    <?php
    
    return (object) array(
        'host' => 'localhost',
        'username' => 'root',
        'pass' => 'password',
        'database' => 'db'
    );
    
    ?>
    

    This allows you to use the object syntax when you include the php : $configs->host instead of $configs['host'].

    Also, if your app has configs you need on the client side (like for an Angular app), you can have this config.php file contain all your configs (centralized in one file instead of one for JavaScript and one for PHP). The trick would then be to have another PHP file that would echo only the client side info (to avoid showing info you don't want to show like database connection string). Call it say get_app_info.php :

    <?php
    
        $configs = include('config.php');
        echo json_encode($configs->app_info);
    
    ?>
    

    The above assuming your config.php contains an app_info parameter:

    <?php
    
    return (object) array(
        'host' => 'localhost',
        'username' => 'root',
        'pass' => 'password',
        'database' => 'db',
        'app_info' => array(
            'appName'=>"App Name",
            'appURL'=> "http://yourURL/#/"
        )
    );
    
    ?>
    

    So your database's info stays on the server side, but your app info is accessible from your JavaScript, with for example a $http.get('get_app_info.php').then(...); type of call.

    0 讨论(0)
  • 2020-11-27 11:01

    Well - it would be sort of difficult to store your database configuration data in a database - don't ya think?

    But really, this is a pretty heavily opinionated question because any style works really and it's all a matter of preference. Personally, I'd go for a configuration variable rather than constants - generally because I don't like things in the global space unless necessary. None of the functions in my codebase should be able to easily access my database password (except my database connection logic) - so I'd use it there and then likely destroy it.

    Edit: to answer your comment - none of the parsing mechanisms would be the fastest (ini, json, etc) - but they're also not the parts of your application that you'd really need to focus on optimizing since the speed difference would be negligible on such small files.

    0 讨论(0)
  • 2020-11-27 11:02

    You can create a config class witch static properties

    class Config 
    {
        static $dbHost = 'localhost';
        static $dbUsername = 'user';
        static $dbPassword  = 'pass';
    }
    

    then you can simple use it:

    Config::$dbHost  
    

    Sometimes in my projects I use a design pattern SINGLETON to access configuration data. It's very comfortable in use.

    Why?

    For example you have 2 data source in your project. And you can choose witch of them is enabled.

    • mysql
    • json

    Somewhere in config file you choose:

    $dataSource = 'mysql' // or 'json'
    

    When you change source whole app shoud switch to new data source, work fine and dont need change in code.

    Example:

    Config:

    class Config 
    {
      // ....
      static $dataSource = 'mysql';
      / .....
    }
    

    Singleton class:

    class AppConfig
    {
        private static $instance;
        private $dataSource;
    
        private function __construct()
        {
            $this->init();
        }
    
        private function init()
        {
            switch (Config::$dataSource)
            {
                case 'mysql':
                    $this->dataSource = new StorageMysql();
                    break;
                case 'json':
                    $this->dataSource = new StorageJson();
                    break;
                default:
                    $this->dataSource = new StorageMysql();
            }
        }
    
        public static function getInstance()
        {
            if (empty(self::$instance)) {
                self::$instance = new self();
            }
            return self::$instance;
        }
    
        public function getDataSource()
        {
            return $this->dataSource;
        }
    }
    

    ... and somewhere in your code (eg. in some service class):

    $container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection
    

    We can obtain an AppConfig object from any place in the system and always get the same copy (thanks to static). The init () method of the class is called In the constructor, which guarantees only one execution. Init() body checks The value of the config $dataSource, and create new object of specific data source class. Now our script can get object and operate on it, not knowing even which specific implementation actually exists.

    0 讨论(0)
提交回复
热议问题