1
I’m building classes for an old project where I used only functions in different files. The goal is clear, to create a reusable code standard for small-scale projects with not very distinct functionalities, and on condition that it can be improved/modified in the future without major efforts.
Currently the project acts as a mini-blog, which is something really simple, I also ruled out the possibility of using some kind of framework.
Área Pública:
- Read content.
- Comment on.
- Play video.
- Browse between categories.
Administrative Area:
- Edit/Remove Content.
- Edit/Remove Comments.
- Add/Remove/Edit administrators.
- Add/Remove/Edit categories.
- In/out.
It turns out I’ve always programmed using the procedural style, and in that I manage almost all my experience in web programming, I also program using the oriented style, but not as often as I’ve been developing the procedural way, so let’s just say I have little experience with POO for the simple fact of not knowing much of its applications and its problems in the real world.
Once I mapped out a schematic for this application that I’m developing, I concluded that I would have no problem using the pattern Singleton. It turns out that so far I have not found a specific case where it is stated that this pattern can be used without problems, since in most of the research, more have been reported low than highs.
I have with me this kind of connection:
class Database {
static $_instancia,$_erro=false;
private $_pdo,$_resultado,$_query;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.Padrao::get('mysql@host').';dbname='.Padrao::get('mysql@dbname').';charset='.Padrao::get('mysql@charset').';', Padrao::get('mysql@usuario'), Padrao::get('mysql@password'));
} catch(PDOException $e){
die($e->getMessage());
}
}
// Singleton
static function getInstance(){
if(is_null(self::$_instancia)){
self::$_instancia = new Database();
}
return self::$_instancia;
}
// Select (também auxiliar às restantes acções - CRUD)
public function query($tabela, $where){
$campo = $where[0];
$operador = $where[1];
$valor = $where[2];
$sql = "SELECT * FROM {$tabela} WHERE {$campo} {$operador} ?";
if($this->_query = $this->_pdo->prepare($sql)){
if($this->_query->bindParam(1, $valor)){
if($this->_query->execute()){
$this->_resultado = $this->_query->fetchAll(PDO::FETCH_OBJ);
return $this;
} else {
self::$_erro = $this->_query->errorInfo()[2];
}
}
}
return false;
}
// Resultados
public function resultado(){
return $this->_resultado;
}
// Erro na consulta
public static function erro(){
return self::$_erro;
}
mais métodos...
}
It has a CRUD and the instance itself, the class itself is complex, I edited this one and removed some of the methods, yet I kept in it the essential.
Next I have class Config
also responsible for most of the configurations, in the various classes, and some useful methods:
// Classe para configurações
class Padrao {
static function get($path = null, $config=null){
if(!empty($path)){
$path = explode('@',$path);
// Parte do ficheiro de configuração (adaptado para o exemplo)
$array = array('mysql'=>array
('host'=>'127.0.0.1','dbname'=>'exemplo','charset'=>'utf8','usuario'=>'root','password'=>''),'outros'=>array());
//Padrao para o caso de não serem especificados dados externos
$config = !isset($config) && empty($config) ? $array : $config;
foreach($path as $part){
if(isset($config[$part])){
$config = $config[$part];
}
}
return $config;
}
return false;
}
/*
static function path(){...}
...
*/
}
In the first method of this class, I created the variable $array
as default values for that method, just for this example, they usually don’t even exist in that method, because they are brought from the configuration file, where I store the constant and other values predefined.
Finally, I have this part, where I create an instance of this connection, and return all existing entries in the database, as they are usually done on main pages.
$database = Database::getInstance()->query('exemplo',array('id','>','40'));
if(!Database::erro()){
foreach($database->resultado() as $object){
print $object->id . " - " . $object->titulo . "<br/>";
}
} else {
echo Database::erro();
}
The method erro()
was defined as static
because I needed access to the value of $_erro
from outside this class.
Doubt:
Based on the type of project I intend to build and the features I intend for this project, the standard Singleton is really ideal?
What mistakes have I made yet in this little development?
Related: Why shouldn’t we use Singleton? and How to make a database connection using the Singleton design standard
– rray
Like, I’ve read these answers over and over, and right now I’m more concerned about compatibility, and whether I’m programming in the right way, taking into account the type of project, especially by "criticism" that this pattern received.
– Edilson
Relax, wear Singleton where you need it and don’t use it where you don’t need it and you’ll be fine. Some classic examples where you might need it: database connection manager and message queue manager.
– Caffé
Okay, thanks for the tip, anyway I’m almost done with the general classes, soon I’ll be renewing the layout. Nevertheless, I shall await a possible response based on practical examples.
– Edilson