Reputation: 3196
I'm working on developing an API. Started with a concept last year and have been developing on it since then. Over the course of the year, the structure and offerings have changed greatly and I am finding it a headache to update my class structures. Granted, I started designing this new to PHP and MongoDB, also new to the concept of web programming and servers getting and sending data and databases in general. I have a decent understanding of how the two work together now, but I believe my initial approach to class design is wrong. Well, I guess not wrong, but not designed as well as it should be.
Currently, I have 4 main classes. We'll call them class A, B, C, and D.
Now, class A, B, and C are all objects that represent the documents that are stored in 3 separate MongoDB Collections. Class D represents a monster class that handles interactions between the other three objects. I felt it was wrong to have objects modifying other objects inside of them.
Objects A, B, and C all have connections to MongoDB inside of their __construct() function. Is this a correct approach? Is it good practice to have object handle their own connection to the database?
Thanks in advance for the help!
Upvotes: 0
Views: 168
Reputation: 62648
This is generally a bad idea unless you have a pooling connection manager from which objects acquire their connections. Connection setup is expensive, and you have a finite number of connection slots.
Generally speaking, you'll want one connection per thread, which objects then use. This may be varied based on your application's needs, but at a minimum, use a connection pool rather than one connection per instance.
Upvotes: 2