Search code examples
phpdatabaseoopclassfilestructure

How do I organize classes in PHP and access database from within class


I have been programming procedural PHP for about 8 years, and am finally starting to learn OOPHP. I've gone through many many tutorials and I understand the syntax and feel quite comfortable using it. What I've failed to find, though, is a practical example of how to setup the class file structure, and how to access my database from within classes to perform queries in them.

my initial thought was to create a separate folder called /class and make a file for every class. if a class extended another class, i would include() the parent file in the child file. in my main scripts i would call classes as i need them. for example include(/class/member.php) when i needed them member class.

also, i wrote a database class that extends mysqli (i know many of you will suggest i use PDO instead, and if you have some reasons why feel free to offer them, although i will say i don't expect to ever not use MySQL). The part that really threw me was how to open the database connection in my classes. for example, my thought was in the member class I would pass a member_id, and then i would execute a query in the class to set all of its properties to that of the member. Initially i included the database class in my main script and made an instance of it, and then declared the handle as global in my member class (I've read how globals are evil, and i don't really like that solution anyway). what is a better way to do this?

thanks for any help!


Solution

  • First, you're definitely on the right track with the separate file for each class. This is pretty much considered standard practice at this point. I would look into class autoloading and spl_autoload_register. I highly recommend setting up an autoloader first thing, trust me when I say you really don't want to have to do countless interface_exists and class_exists calls before you include your class files.

    Second, about your database calls. I answered a similar question here but the basic gist is that you create a single database instance and inject that into the classes needing database access. As far as mysqli, if that is what you like using go for it. Its awesome that you aren't using the older, deprecated mysql_*.