I am a newbie CodeIgniter developer and I must say my frustration rached to new heights when I realized I wasn't able to make work a very simple click counter. The idea is you click on a button and get the number of clicks counted. This is the view simplecounter_view:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');?>
<html>
<body>
<?php
echo '<form action="'. base_url().'index.php/simplecounter" method="POST">';
echo '<font color="blue">Click counter:' . $counter . '</font><br/><br/>';
echo '<input type="submit" name="myform" value="Count">';
echo '</form>';
?>
</div>
</body>
</html>
If you click the form button it will call the SimpleCounter Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class SimpleCounter extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index() {
$myform=$this->input->post('myform');
if ($myform=='Count') {
Globals::setCounter(Globals::getCounter()+1);
}
$data['counter'] = Globals::getCounter();
$this->load->view('simplecounter_view', $data);
}
}
Finally, I am using a Globals class with the property $counter in order to keep its value "global" and accessible from the Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Globals {
private static $initialized=false;
private static $counter;
private function __construct() {}
private static function initialize() {
if (self::$initialized)
return;
self::$counter = 0;
self::$initialized = true;
}
public static function setCounter($n) {
self::initialize();
self::$counter = $n;
}
public static function getCounter() {
self::initialize();
return self::$counter;
}
}
The code above doesn't work as I expected. The click counter doesn't get updated on every user click. It seems to me the Globals class gets recreated every time one of its methods is called and so $counter is reset to zero and $initialized to false.
I understand there might be different approaches (like defining $counter in config.php) though I think using a separated class for keeping $counter is more elegant. What am I missing here? Where did I get it all wrong? Your help is much appreciated.
Since HTTP is stateless protocol, once the http response is sent to the requesting browser all your variables get lost.
In computing, a stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of request and response.
You need to save the counter in a database.