How to create and access a global variable with PHP and codeigniter

0

Good morning, I'm having a question, I'm using the following to generate success alerts or errors on my system.

if ($this->model->inserir($data)) {
    $msg = "<div class='alert alert-success'> Cliente salvo com sucesso</div>";
    $this->session->set_flashdata('mensagem', $msg);
    redirect('clientes');
} else {
    $msg = "<div class='alert alert-danger'> Erro ao inserir cliente</div>";
    $this->session->set_flashdata('mensagem', $msg);
}

Look, I have a lot of controllers and inside of these controllers several methods, if I put this in each method it will be very laborious.

I would like to know if I can create the variable $ msg of global froma to be accessed by any controller / method and where I create it.

    
asked by anonymous 08.02.2017 / 13:33

2 answers

1

So I understand, it's not about creating another "global variable" , but about a function that reads SESSION , which is already global. Whenever you need to create a function (or method) that should be accessed globally, use a HELPER , a HOOK or a library.

My suggestion: create a HELPER that will read the SESSION mensagem and return a alert formatted according to the method command .

Create applications / helpers / session_helper.php :

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

if( ! function_exists('session_alert')){
    function session_alert(){
        if(isset($_SESSION['mensagem'])){
            echo '<div class="alert alert-'.$_SESSION['mensagem'][0].' alert-dismissible" role="alert">';
            echo '<button type="button" class="close" data-dismiss="alert"';
            echo 'aria-label="Close"><span aria-hidden="true">&times;</span>';
            echo '</button><strong>Aviso!</strong> '.$_SESSION['mensagem'][1];
            echo '</div>';
        }
        unset($_SESSION['mensagem']);
    }
}

Load the HELPER with autoload : $autoload['helper'] = array('session_helper');

Your controller will create warnings the same way, just passing an array with message data to $_SESSION['mensagem'] :

if ($this->model->inserir($data)) {
    $this->session->set_flashdata('mensagem', ['success','Cliente salvo com sucesso']);
    redirect('clientes');
} else {
    $this->session->set_flashdata('mensagem', ['danger','Erro ao inserir cliente']);
}

As you can see, the session_alert() function will only show the alert when there is data in $_SESSION['mensagem'] . So you can call this function in VIEW using <?= session_alert(); ?> in any VIEW of the system.

For example, your VIEW "clients" might look something like this:

<html>
 <body>
  <?= session_alert(); ?>
 </body>
</html>
    
08.02.2017 / 21:22
0

Use $ GLOBALS as follows:

$GLOBALS['msg'] = $msg;

And within each function you can call it like this:

global $GLOBALS;
$msgGlobal = $GLOBALS['msg'];

I suggest using it as I do not know the number of classes and functions you have.

    
08.02.2017 / 13:44