views:

82

answers:

3

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?

+1  A: 

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.

txwikinger
+5  A: 

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();
    }

}
Bart van Heukelom
Yeah, I would look at storing the data object in a separate class and interacting with it that way.
tsgrasser
i am talking about a logger class which logs things to DB.the initialization code for this class is the same for all instances.......doesn't it make the case for a singleton?
rahul
Yes, but it shouldn't be a Doctrine model then. Instead it will use separate class LogEntry or something which is such a model.
Bart van Heukelom
how can we insert something into a DB if it is not a Doctrine Model?
rahul
You can't, but you're not inserting loggers into the database are you? ;) You're inserting log entries, and that would be the model class, used by the logger. I've added some pseudocode to my answer to explain this.
Bart van Heukelom
thank you.....i was just trying to do it in one class....so i was searching if we can insert using Doctrine_Table (Zend_Db_Table allows inserting records into DB)
rahul
A: 

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.

Justin Giboney
What are you on about?
Bart van Heukelom