How to create and access a global variable with PHP and codeigniter
Good Morning folks, I'm having a doubt I'm using the following to generate success alerts or errors in 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);
}
See that I have several controllers and within these controllers several methods if I'm going to put this in each method it will be very laborious.
I would like to know if I have how to create the FR MSG variable from froma global to be accessed by any controller / method and where I create it.
2 answers
As I understand it, it's not about creating another "global variable", but a function that reads the session, which is already global. Whenever you need to create a function (or method) that should be accessed in a"global" way, 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.
Shouts 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 in the same way, only passing a 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 function session_alert()
will only show the alert when there is data in the $_SESSION['mensagem']
. Thus, you can call this function in VIEW using <?= session_alert(); ?>
in any View of the system.
For example, your View "clients" might have something like this:
<html>
<body>
<?= session_alert(); ?>
</body>
</html>
Uses glob GLOBALS as follows:
$GLOBALS['msg'] = $msg;
And within each function you can call like this:
global $GLOBALS;
$msgGlobal = $GLOBALS['msg'];
I suggest using this way because I don't know the number of classes and functions you have.