BobbyP
BobbyP

Reputation: 2245

Advice on database connection within PHP class

I am playing around with OOP programming, and have hit a hurdle I could use advice with.

I have a situation where I have nested classes. I have a "Company" class, which contains an array called people. This array contains many instances of a "Person" class.

The data for both 'company' and 'person', are stored within a database, and the relevant class retrieves the information from that database as and when it is needed.

My question quite simply is this: "At what point do I connect to the database?" Do I:- a) Connect first in my PHP page, then pass the connection to the instance of "Company" for it to use. b) Put the username, password etc directly in the "Company" class and connect there.

I would have thought that the latter would create multiple connections to the database - one for each instance of "Company" - so probably the answer is "A". But then, if I were to pass the class to another developer (this is only a learning exercise, so not something I plan to do), he would have to connect to the database himself, and not allow my class to do it for him.

In either case, would the connection be passed to each instance of the "Person" class automatically, or would I have to pass the connection each time I create a new instance?

I have done some research on this, and I think the answer is "A" (connect to the database in my PHP page, and pass the connection to each instance of the Company class), but just thought I should double check before I get too far.

Thanks for any advice you are able to offer.

Upvotes: 0

Views: 211

Answers (2)

regulatethis
regulatethis

Reputation: 2352

I think you're on the right track.

What you're describing is known as dependency injection and using it is generally a good idea.

When you're dealing with a more complex project, it might be a good idea to abstract the retrieval of data completely. Create an interface, i.e. "PersonFinder" or "CompanyFinder" that deals only with the lookup and retrieval of its associated records. Concrete implementations of this interface might include database lookups, or CSV file lookups, or even some sort of web-based service lookup. Pass your Finder into your Company or Person objects when you create them.

This way you can easily change how you find your records without changing the code that deals with them.

Upvotes: 0

feeela
feeela

Reputation: 29922

You solution A) sounds familiar to me. That way you can just pass the database connection to the object or maintain a global registry to store the connection object (e.g. PDO) into.

Upvotes: 1

Related Questions