Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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 "form1", second "form2" 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?



34.8k

Try with return $this->counte++;

Now it only returns 0 every time.



7.2k
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!