Advice on database connection within PHP class -


i playing around oop programming, , have hit hurdle use advice with.

i have situation have nested classes. have "company" class, contains array called people. array contains many instances of "person" class.

the data both 'company' , 'person', stored within database, , relevant class retrieves information database , when needed.

my question quite this: "at point connect database?" i:- a) connect first in php page, pass connection instance of "company" use. b) put username, password etc directly in "company" class , connect there.

i have thought latter create multiple connections database - 1 each instance of "company" - answer "a". then, if pass class developer (this learning exercise, not plan do), have connect database himself, , not allow class him.

in either case, connection passed each instance of "person" class automatically, or have pass connection each time create new instance?

i have done research on this, , think answer "a" (connect database in php page, , pass connection each instance of company class), thought should double check before far.

thanks advice able offer.

i think you're on right track.

what you're describing known dependency injection , using idea.

when you're dealing more complex project, might idea abstract retrieval of data completely. create interface, i.e. "personfinder" or "companyfinder" deals lookup , retrieval of associated records. concrete implementations of interface might include database lookups, or csv file lookups, or sort of web-based service lookup. pass finder company or person objects when create them.

this way can change how find records without changing code deals them.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -