How to save data to a global array

Asked

Viewed 781 times

5

I am studying PHP, and so far I have developed a small system that "mounts" the site views and etc.

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

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

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

The problem is that I am working with classes to make the system. And I can’t pass this array between the system classes. For example, I’m working on a class function Database and I want to keep a mistake that happened there but the function of echo is only shown in the class System.

Check my code so far:

php system.

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 of showing bugs. I’m running tests for the on function else of the archive 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.

  • 2

    Wouldn’t it be easier then to create a function (or exaggerate, a separate class) to store the errors? And in addition, you can use PHP’s own error log with your custom messages instead of making a new system. Click here: error_log()

1 answer

5


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

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

But this is a terrible idea.

At the very least I could create a class Singleton to store this data and catch them through this class. Still not the best solution.

Actually, the whole system that you’ve built seems like a bad idea of how to deal with the problem. Including one class within the other, for example, is not a good idea. I think you’re not getting what you need and you’re creating some crazy code. Don’t get attached 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 very well, it has to be something clean.

It has used syntax that seems to me very strange too.

Of any the objective answer was given and a more viable alternative also. Bacco gave another option in the comment of the question.

  • So, like I said. I’m just studying, testing, seeing possibilities, I don’t really understand how it works, at this beginning as in the beginning of anyone I go through what I see in other people’s code. But thank you for the information, and I will study what you recommended too.

  • This is why I gave additional information. This for example is very strange for me: new Database;&#xA; (new Database)->setup(); Suggestion for reading: http://answall.com/q/21158/101

  • Oh no, that’s just for testing, it won’t stay in the final code. I needed to check if the setup functions were working properly, while not finishing the part responsible for checking whether the system is already installed or not.

Browser other questions tagged

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