1

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!

2 Answers 2

5

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_*.

5

In my opinion, the best way to learn OOP is to view already existing codebases which follow OOP. I would suggest checking out the Zend Framework API Docs. If it looks promising to you, download the framework and start practicing with it.

The cool thing about Zend Framework is it can be used as a top down MVC, or a stand-alone library, and is heavily used in the PHP community.

Some things to concentrate on:

  • Class autoloading
  • How class names line up with their respective directory structs
  • How classes are extended
  • Interfaces
  • Abstract classes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.