1

I'm trying to implement an instance counter on a php/symfony3 project, but I don't find how.

I have an "Advert" entity, and I want to show how many instances exist on a Twig view.

So, in the entity class, I created a static attribute private static $nbAdverts = 0; with a getter/setter, and two static methods:

/**
 * @ORM\PrePersist
 */
public static function increaseAdverts()
{
    self::$nbAdverts++;
}

and

/**
 * @ORM\PreRemove
 */
public static function decreaseAdverts()
{
    self::$nbAdverts--;
}

I'm calling these methods using the Doctrine events: PrePersist and PreRemove.

These adverts are created in the controller using the Advert repository before being persisted and flushed. Also called using this repository before being removed.

The counter remains stuck at 0 when I add or remove an advert.

I think I'm doing something wrong: is it possible to do this without rewriting the repository add method? If it is, any idea about how?

1
  • You are talking about two static methods, one supposed to increase adverts and the other to decrease them but you posted the increaseAdverts twice Oct 14, 2018 at 21:49

1 Answer 1

0

The behavior you are getting is absolutely normal. You are running a web application, any variable not stored in the session, is set to it default value if exists, at every request. So to achieve what you want to do you can save your static variable in session and update it in the increaseAdverts() and decreaseAdverts() Methods.

2
  • Thanks for your answer. But, if I save this static variable in the session, she will be reset after the end of the session, right? And I also will have to do a request to know how much instances are created to initialize the variable? Oct 14, 2018 at 22:56
  • What you do is that when initiating the session (for example when user login) you initiate a db query where you count all the instances in db. And during the session when a new element is created or deleted, you update the session variable. Note that with this approach different users will have different values at the same time, because they are not sharing the same session. Another alternative will be to read the data from db at every request, it's heavy for db, but with this approach all the users will have the same number at the same time. Oct 14, 2018 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.