We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

A global incrementor service in Phalcon

I try to create a service in Phalcon, that only increments a number.

My Class:

<?php
class FormCounter {

    private $counter = 0;

    public function increment() {
        $this->counter++;
        return $this->counter;
    }

}

In services:

$di->set('formCounter', function () {
    return FormCounter();
});

In my Form Class I want to create an ID in every form with increments. The first form i create will have ID "form_1", second "form_2" etc.

$this->form_id = $this->getDi()->getFormCounter()->increment();

But it won't increment. It returns 1 everytime. How do I do this without using global variables?



58.4k

Try with return $this->counte++;

Now it only returns 0 every time.



8.1k
Accepted
answer
$di->set('formCounter', function () {
    return FormCounter();
});

New object FormCounter created when you call it in this set. Try to set service as shared

$di->setShared('formCounter', function () {
    return FormCounter();
});

Perfect! Thanks!