views:

66

answers:

7

How should I store settings for project?

Which is better - to use a $settings array with all my settings:

$settings['max_photos'] = 30;
//...

or create a singleton Config class with all the settings in it?

Class Config {
    private $max_photos = 30;
    //...
}

Any good examples?

A: 

The best way is to store your setting in a file . and to manipulate this file declare a class which does operations on file

sagar
A: 

If the project settings is too heavy, then file(xml is better) is good and a dedicated class for settings is also good.

If the project settings is small, then array is best, its very fast and no I/O related issue will arise.

Even you can use database (slower and auth issue).

Sadat
+1  A: 

Either will work nicely, do whichever you feel most comfortable with.

Toby Allen
+3  A: 

I think it is best to use constants for configuration. For example using class constants:

class Config {
    const
    max_photos     = 30,
    something_else = 100,
    // ...
    ;
}

echo Config::max_photos;

If you have PHP 5.3 you could also define them as global constants:

const MAX_PHOTOS = 30;

echo MAX_PHOTOS;

But I think this is far less clean and straightforward.

Obviously this will only work as long as you are only storing constants, i.e. scalar, non-expression values. If your configuration contains arrays for example, this won't work anymore. In this case I would use a Config class with public static properties:

class Config {
    public static $per_page = 30;
    public static $array = array(...);
}

echo Config::$per_page;

The latter is very similar to the $config array approach, but has the benefit (or may this be a drawback?) that the class is accessible from everywhere including functions and classes, whereas the array is accessible only in the global space unless you import it into functions/classes using global $config;.

nikic
+1 constants for constant values, then you can be assured they are always set, unchangeable and persistent; fwiw static class variables carry a performance hit and can be changed at runtime. Finally, incase anybody suggests a config ini or xml file - the simple response is, why waste the time and add in extra load that isn't needed (parsing reading etc).
nathan
thanks, yes, i got arrays too:$settings['languages'] = array( 'eng' => 'In English', 'rus' => 'По-русски', 'lat' => 'Latviski');$settings['site_title'] = _("Site title");$settings['default_lng'] = 'eng';/** * Мин. количество гололов */$settings['min_votes'] = 3;/** * Кол-во пользователей, после которого регистрация только по приглашениям. */$settings['invites'] = 100000;//25000;/** * Время истечения приглашения */$settings['invite_timeout'] = 86400 * 3;i think, this variant is better, thank you all for help!
ideea
A: 

The best way is to store the Settings in your Database, but in some case this is not important, than you can use an array in a settings.php or config.php

This can look like this: (settings.php)

<?php
$settings = array();

/* MAX_PHOTOS */
$settings['max_photos'] = 30;

/* MAX_WIDTH */
$settings['max_width'] = 30;
?>

and the best way is to get the settings with an class (settings.class.php), in this case settings.class.php and settings.php should be in the same folder, you can change it :)

Here an example of a settings.class.php

<?php
require_once( 'settings.php' );

class Settings
{
    public $s;

    public function __construct()
    {
        global $settings;

        $this->s = $settings;
    }

    /* CHANGE $this->get_normal to $this->get_db, if you want to use it with a Database */
    public function get( $get )
    {
        return $this->get_normal( $get );
    }


    public function get_normal( $get )
    {
        if( isset( $this->s[trim( $get )] ) )
        {
            return $this->s[trim( $get )];
        }

        return FALSE;
    }

    public function get_db( $get )
    {
        $db_connect  = mysql_connect('HOST', 'USER', 'PASSWORD');
        $db_select = mysql_select_db( 'DATABASE' );

        $query = sprintf( "SELECT * FROM settings WHERE key='%s'", mysql_real_escape_string( trim( $get ) ) );
        $db_query = mysql_query( $query );

        mysql_close( $db_connect );

        if( $db_query )
        {
            while( $array = mysql_fetch_array( $db_query, MYSQL_ASSOC ) )
            {
                return $array[ trim( $get ) ];
            }
        }

        return FALSE;
    }
}
?>

and if you need later a Database, you can change only the class and you have not to change your whole sourcecode.

You can change $this->get_normal to $this->get_db, if you want to use it with a Database, I have not tested the Database Query and the Database Connect, but this is only an example how it would look like :)

I hope it helps you!

ahmet2106
if you are rating negative, than please say why!
ahmet2106
+1  A: 

If you go for the array approach, you could use array literals for slightly more readable code:

$settings = array(
    'max_photos' => 30,
    'max_width'  => 100
    //...
)
Eric
A: 

My two cents: Use both. Most application configuration settings belong in a global array variable. Config data needs to be accessible from diverse application parts, and this is what global variables are for. And keeping everything together in a an array is most sensible. An array can be extended, e.g. some options set in a config.php and the rest read from a config.ini for example.

But there is also a place for CONSTANTS. The fine line to draw is, if an option is really something that MIGHT change during the application runtime, or if it is more a of fixed/magic value. If once set up, you should not change an application setting (or rendering might fail), then this option shouldn't be in the array, but sementically fixed as constant. (That's an interpretative rule of thumb, but served me well.)

mario