How to store a website settings?

Asked

Viewed 185 times

9

I intend to develop a site that has some configuration options, for example:

  • Maintain standard or custom logo
  • Allow registration of new users
  • Authorize anonymous comments in posts

How should these settings be kept? Remembering that there is a control panel where the user can change them.

  • 2

    It’s not the same question, but I asked that a while ago. http://answall.com/questions/98960/%C3%89-recommended-the-use-of-constants-for-configure%C3%A7%C3%B5es-of-a-project-in-php - Maybe it can be useful.

2 answers

7


Depends on the way you need it.

The simplest way is to put this information into global variables or encapsulated in some way (a array, a class, etc.). This usually works well if it cannot be changed by users. You can even let the user change, but it’s not worth the hassle to do it right.

If the user (different from the programmer or the application installer) can configure this as indicated in the question, then it would be better to store elsewhere. It can be a simple file, or better still would be put in a database, especially if the application already uses a.

What would I do

In general a simple table with a column for each possible configuration is usually sufficient. Most columns will be boolean, but nothing prevents you from having any configurable information.

If you want to generalize more, you can create a table that allows the user to define their own settings. Of course, it helps little if the code doesn’t know what to do with them.

A simple table is sufficient for the general configuration. If you have more specialized settings, per user for example, you have to have a column indicating to whom that specific value belongs, and the application needs to know how to read this according to the user.

That’s the important part to store. Then you have to think about whether it’s worth having some optimizations to avoid access to the database every time you need one of these settings. You have to think about whether you should have a way to abstract access and allow the storage method to be changed in the future.

Anyway, there is a lot that needs to be thought about. But the question has no details, I can only answer in general lines.

3

I usually create a class app_config, and its instance right in the index of the application with the current directory and indicate a configuration file config.ini.php with the settings, in your content I put:

;<?php
;die("Se quiser, coloque uma mensagem de erro aqui caso o usuário tente acessar esse arquivo");
;/*

[db]
usuario=user;
senha=pass;
host=localhost;
database=db;
chatset=utf8;

PS: I used the database example which is as generic as possible, there are cases that you will need to use another type of authentication in your database and will not store the passwords so, everything depends on your project, if it is something simple, there will be no problem. I’ll explain why the .ini.php

Creating the archive .ini.php and putting these comments above is useful when you or your client use a shared hosting and have no way of putting off the public_html of the project, there will be no risk of the user downloading the .ini.php, whether or not containing any rule in htaccess.

And here the class app_config to read the file.

class app_config
{
    private $ini;
    private $projeto_dir;

    /** método construtor, recebe o caminho completo do sistema para o 
        arquivo ini, e então verifica sua existência **/
    public function __construct($arquivo, $projeto_dir)
    {
        try
        {
            $this->ini = parse_ini_file($arquivo,true);
        }
        catch (Exception $e) 
        {
            die('Não foi possível encontrar o arquivo de configuração solicitado, a execução não poderá continuar');
        }
        $this->projeto_dir = $projeto_dir;
    }

    /** 
      * Retorna o valor da sessão e parâmetro solicitado
      *
      * Requer um arquivo de configuração válido 
      *  
      * @name get
      * @access public
      * @return string 
    **/
    private function get($sessao,$parametro)
    {
        return $this->ini[$sessao][$parametro];
    }

    /** 
      * Retorna o usuário do banco de dados
      *
      * @return string
    **/
    public function get_db_usuario() 
    { 
        return $this->get('db','usuario'); 
    }

    /** 
      * Retorna a senha do banco de dados
      *
      * @return string
    **/
    public function get_db_senha() 
    { 
        return $this->get('db','senha'); 
    }
}

So when necessary, you can inject your instance into some class that uses your methods.

// A instância da index pega o diretório do projeto com dirname(__FILE__)
    $config = new app_config('local/para/sua/config/config.ini.php', dirname(__FILE__));
    $projeto = new projeto_exemplo($config);

Within your class you intend to inject these settings, have a type attribute app_config to receive the object we will pass by parameter.

This technique of injecting what you need into a class is known as dependency injection.

Within the example, we can then call the methods of the app_config.

$db = $this->config->get_db_usuario();

The class I gave you is just a sketch, mine is huge and very specific to my project, but this is the logic I use.

Perks

  • Does not create global objects.
  • Does not use constants that can be visible to the whole project.
  • It’s completely object oriented.
  • It uses the encapsulation.
  • Can read . ini files outside and inside the public_html
  • Depending on your project, it can be reused.

Disadvantages

  • It’s more work than a simple global constant, but hard work in this case is welcome.

You can also set/get methods to get database information, just implement methods that do this directly in this class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.