1

Each time I process a post, the code runs thru a function in my own MyController extends AppController class. That function calls this function to obtain a unique context number. The idea is that this number should be retained from one post to the next (or one run thru the Controller class function to the next). But instead the Configure::check() always fails and the unique32 is always created anew, so this function always returns 1.

Does anyone know how to make the Configure::write() get retained from one post to the next?

public function getUnique32() {
    if (!Configure::check('unique32')) {
        $unique32 = 0;
        echo "unique32 starts at 0";
    } else {
        $unique32 = Configure::read('unique32');
        echo "unique32 is $unique32";
    }
    if (++$unique32 >= 0xffffffff) {
        $unique32 = 0;
        echo "unique32 is reset to 0";
    }
    Configure::write('unique32', $unique32);
    return $unique32;
}
Inigo Flores
  • 4,461
  • 1
  • 15
  • 36
Joe C
  • 2,728
  • 4
  • 30
  • 38

1 Answers1

1

Class Configure does not persist data between page requests. Use instead class Session.

In CakePHP 3.x, your code should be written as follows:

public function getUnique32() {

    $session = $this->request->session();
    if (!$session->check('unique32')) {
        $unique32 = 0;
        echo "unique32 starts at 0";
    } else {
        $unique32 = $session->read('unique32');
        echo "unique32 is $unique32";
    }

    if (++$unique32 >= 0xffffffff) {
        $unique32 = 0;
        echo "unique32 is reset to 0";
    }

    $session->write('unique32', $unique32);
    return $unique32;
}

For CakePHP 2.x, you can replace one class for the other in your code.

From the Cookbook 3.x:

Inigo Flores
  • 4,461
  • 1
  • 15
  • 36
  • Good thing to know. May I ask how long Session persists? Until there's a "service httpd restart" was what I was looking for. BTW, that seems like a serious omission from CakePHP documentation, unless you know where the quote is. – Joe C Jan 08 '16 at 22:13
  • Sessions last for as long as specified. See http://stackoverflow.com/questions/14470018/cakephp-session-timeout-on-inactivity-only . Sessions survive `service httpd restart`, as they are based on cookies and sess_xxxxxx files that are only cleared when they expire. – Inigo Flores Jan 08 '16 at 22:23
  • OK, I guess surviving across restart is OK too. Last question. Simply replacing one class for another doesn't work. Do I need a "use" statement and / or "require_once" statement? Or do I need to initialize the session? And are you sure it's not supposed to be "CakeSession" instead of "Session". – Joe C Jan 08 '16 at 22:31
  • I just realised you are using CakePHP 3.x. Will edit my answer. – Inigo Flores Jan 08 '16 at 22:33