Tutorial :Singleton Models Doctrine


Can we have a model class which is singleton in Doctrine?

For Singleton classes I should have a private/protected constructor....but this is not possible as I am extending a Doctrine class which has a public constructor

You can argue about the use of the Singleton pattern when interacting with the DB, but just consider this scenario:

I have a user action logger which logs to the database. This logger does some initialization in the constructor (getting the current users information from the session) which is common for all instances of the logger for a particular execution.

There seems to be no way to implement the singleton pattern for models when using Doctrine?


An instance of a Doctrine model class corresponds to one entity, e.g. an instance of User represents one user, and I doubt you have only one of those. Put your other code in a separate class, UserManager or something.

class Logger { // plain old singleton class        function log(x) {          entry = new LogEntry(x); // LogEntry extends Doctrine_Model          entry.save();      }    }  


You can override the public constructor in such a way that it uses a singleton factory method that will either create an instance if it does not exists yet, or retrieve the existing instance, and then return the instance to the caller of the constructor.


Your problem doesn't lie in Doctrine, it lies in PHP which is stateless (yes there are some state-like methods of storing an object). Therefore, you can not really ever have more than one of any object at a time anyways.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »