Saving data to a global array

5

I'm studying PHP, and so far I've developed a small system that "mounts" site views and so on.

But I came across an extremely annoying problem that I can not solve. I need a function to show errors that occur in the system.

The problem is that when I use echo to show the messages, it shows the message in the middle of the template (at the beginning of the body tag), not where error messages should appear, which is inside of the tag main .

The solution I found for this was to create a $errors array and save the error messages that I need to show inside it. And then I do a function inside the main tag to give echo in these error messages.

The problem is that I'm working with classes to make the system. And I can not pass this array between the system classes. For example, I'm working on a function in class Database and I want to save an error that happened there but the function of echo is only shown in class System .

See my code so far:

  

system.php

new System;

class System {

    public function __construct() {

        define('config', 'config.php');

        if(file_exists(config)) {
            require_once(config);
        }
        else {
            header('Content-Type: text/html; charset=utf-8');
            echo "<title>Painel de administração - Erro</title>";
            die('Arquivo de configuração não localizado. Contate o administrator do sistema.');
        }

        foreach($required_consts as $value){
            if(!defined($value)) {
                header('Content-Type: text/html; charset=utf-8');
                echo "<title>Painel de administração - Erro</title>";
                die('<strong>Uma configuração do sistema está ausente:</strong> ' . $value);
            }
        }

        require_once('database.php');
        new Database;
        (new Database)->setup();

        require_once('views.php');
        new View($menu, $errors);

    }

    public function error($message) {
        foreach($message as $error) {
            echo "<p class='alert alert-danger'>$error</p>";
        }
    }

    public function success($message) {
        foreach($message as $success) {
            return "<p class='alert alert-success'>$success</p>";
        }
    }

}
  

database.php

<?php

class Database extends System {

    public function __construct() {
        $this->mysqli = new mysqli(host, db_user, db_pass) or die ('Não foi possível conectar ao MySQL: ' . mysqli_connect_error() );
    }

    public function setup() {
        $this->createDatabase();
    }

    public function createDatabase() {
//      $this->mysqli->query("DROP DATABASE IF EXISTS " . db_name );
        $this->mysqli->query("CREATE DATABASE IF NOT EXISTS " . db_name );

        if($this->mysqli->error) {
            return $this->mysqli->error;
        }
        else {
            echo "Banco de dados criado com sucesso.<br>";
            $this->createTables();
        }
    }

    public function createTables() {
        $this->database = new mysqli(host, db_user, db_pass, db_name) or die ('Não foi possível conectar ao Banco de Dados: ' . mysqli_connect_error() );
        $database = db_name;
        $table = users_table;
        $this->database->query("
            CREATE TABLE IF NOT EXISTS users 
            (
                id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
                name VARCHAR(255) NOT NULL,
                email VARCHAR(80) NOT NULL,
                pass CHAR(255) NOT NULL,
                active CHAR(1) NOT NULL,
                admin CHAR(1) NOT NULL,
                register_date TIMESTAMP NOT NULL,
                PRIMARY KEY (id),
                UNIQUE(email)
            )
            CHARACTER SET utf8 COLLATE utf8_general_ci;
        ");

        if($this->mysqli->error) {
            echo $this->mysqli->error;
        }
        else {
            //echo "Tabelas criadas com sucesso.";
            $this->success(['Tabelas criadas com sucesso.']);
            $errors[] = 'Tabelas criadas com sucesso.';
            $this->registerAdmin();
        }
    }

    public function registerAdmin() {

        $query = "SELECT name FROM users WHERE id = 1 AND name IS NOT NULL LIMIT 1";
        $result = $this->database->query($query);
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        if(!$row) {
            $query = "INSERT INTO users(name, email, pass, active, admin) VALUES ('Admin', '[email protected]', md5('adminteste'), 1, 1)";
            $this->database->query($query);
        }
    }


}

Everything works perfect until this part shows the errors. I'm testing the function in else of file database.php .

    else {
        //echo "Tabelas criadas com sucesso.";
        $this->success(['Tabelas criadas com sucesso.']);
        $errors[] = 'Tabelas criadas com sucesso.';
        $this->registerAdmin();
    }

Could someone give me a 'light'? I'm still new to the concept of POO .

    
asked by anonymous 23.12.2014 / 17:58

1 answer

5

What you want is done with global , then you would have to do something like this :

global $errors[] = 'Tabelas criadas com sucesso.';

But this is a terrible idea.

At the very least you could create a class Singleton to store this data and get them through this class. Still, it is not the best solution.

In fact, the whole system you've created seems like a bad idea of how to deal with the problem. Including one class within another, for example, does not seem like a good idea. I think you can not do what you need, and you're creating a cool code. Do not cling to this design that it will bring you problems. If you are going to create your own error management system, you have to think it over well, it has to be something clean.

It has syntax used that seems fine to me too.

Of any objective response was given and a more viable alternative as well. Bacco gave another option in the question comment.

    
23.12.2014 / 18:13