Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
rahul Avatar asked Jun 30 '26 10:06

rahul


1 Answers

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

}
like image 143
Bart van Heukelom Avatar answered Jul 02 '26 04:07

Bart van Heukelom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!