From what I understand, it’s not about creating another "global variable", is a function that reads the SESSION, that is already global. Whenever you need to create a function (or method) that must be accessed in a way "global", use a HELPER, one HOOK or a library.
My suggestion: create a HELPER who will read the SESSION mensagem
and return a Alert formatted according to 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">×</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 the warnings the same way, only passing a array with data from the message to the $_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 function session_alert()
will only show the Alert when there is data in the $_SESSION['mensagem']
. So you can call this function on VIEW using <?= session_alert(); ?>
in any VIEW of the system.
For example, your VIEW "customers" may have something like this:
<html>
<body>
<?= session_alert(); ?>
</body>
</html>