I usually create a class app_config
, and its instance immediately in the index of the application with the current directory and I indicate a configuration file config.ini.php
with the settings, in its 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 example database that is as generic as possible, there are cases that you will need to use another type of authentication in your bank and will not store passwords so, it all depends on your project , if it is something simple, there will be no problem. I already explain why .ini.php
Creating the
.ini.php
file and placing these comments above is useful when you or your client uses a shared hosting and you can not place outside the
public_html
of the project, there is no risk of the user downloading
.ini.php
, even not containing any rule in
htaccess
.
And here is 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 you need it, you can inject your instance into some class that uses its 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 an attribute of type app_config
to receive the object we are going to 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 app_config
.
$db = $this->config->get_db_usuario();
The class I passed is just a sketch, mine is huge and very specific to my project, but that's the logic I use.
Advantages
- Do not create global objects.
- Does not use constants that may be visible to the entire project.
- It is completely object-oriented.
- Use the encapsulation.
- Can read .ini files outside and within
public_html
- Depending on your design, it can be reused.
Disadvantages
- It is more laborious than a simple global constant, but hard work in this case is welcome.
You can also define set / get methods to get information from the database, just implement methods that do this directly in that class.