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">×</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>