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.
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.
– Renan Cavalieri