I've been developing websites using PHP for several years now, yet have never used OOP concepts. I am familiar with them, but have never had a need for them in my projects. However, I am now interested in using them to expand my knowledge, but unsure when they are really needed.

Lets say I have a MySQL database with a "customer" table that stores all their information such as name, address, phone number, etc. The web page will do basic queries on the customer info, inserts, updates, selects, and so forth. I'm trying to incorporate classes with this, yet it seems like it's a lot more work than if I were simply using function to perform the actions on the database. I did some browsing on the web and it doesn't seem like classes are really needed when your dealing with data from a database (other than possible a class to connect to the db). Is this true? Any examples maybe?

    A good reason to consider using classes is that they allow your code at the very top level to be completely isolated from the details underneath. This might be helpful if, for instance, you chose to switch your database engine to postgresql instead of mysql, for instance. rather than having to change a bazillion references to mysql_query() and mysql_fetch_assoc() to something that works for postGRE, then you could just go to the class module where you defined your database and change a handful of functions there. all your code at the top level might not have to change. it might look like this:

    $db->query('select * from table_x');
    

    the basic concept there is called 'encapsulation' or 'information hiding'. this reading may or may not be interesting to you:
    http://en.wikipedia.org/wiki/Information_hiding

    classes are also pretty helpful when you have a really well-defined data object like 'customer'. if you wrote your classes right, you could so something like this at the top level of your code:

    $cust = new customer('Joe', 'Blow', '(555) 555-5555', '123 brooks ave', 'las vegas, NE', '58374');
    $cust->save();
    

    i've had some exposure to classes before and am just now really writing anything interesting. so far, i've noticed a couple of pros and cons to them:

    PROS:
    top level code is really clean looking and easily understood because it isn't jumbled with implementation details and you are permitted to write a function called "save()" for many different objects rather than save_x() and save_y() etc.
    if you create the right classes, it makes moving to a new operating system or database engine much easier. funny thing is you don't need a class to do this...you can just write subroutines that do what you want.
    * i forgot what 3 is.

    CONS:
    If you want to alter the code, you have to go digging around in the appropriate class file to find the relevant code.
    in some cases, it can be a hassle to construct class code. Especially if there are many subtle variations of a single operation that all require arguments, etc. The basic idea is that instead of just writing customer data to a database, you are delegating the writing of that data to another bit of code that you have to write yourself. if every customer gets treated pretty much the same, it can be quite beneficial BUT if every customer has some subtle variation that makes it different every time, it can be tricky.

    jeez, i hope this is helpful. i kind of got lost writing that last point.

      The advantage of classes is that it lets you encapsulate functionality. What this means is that your main code doesn't care about what happens inside a class, all that it cares about is that the methods that are called take the right inputs and return the right values, for instance

      $cust = new Customer() ;
      $cust->name = 'Fred' ;
      $newCustID = $cust->insert();
      

      In the above all that I care about when coding that is that I can set name to 'fred' and that insert() inserts a record and returns a primary key. I really don't care in the least how its done, all that I care about is that it works.

      Yes, this can seem like more work to setup, but consider when you have a more complex system. Your customer class might be used by the following cases

      Customer -> Edits address, login etc.
      Order Class -> retrieves customer data to display with order details
      Admin -> Edit customers
      Store Admin -> Print list of customers within 50 miles

      So lets say all of those uses involve a select query that you have encapsulated into a method called 'findCustomer($id)' and your database structure changes. All you have to do is modify findCustomer(). As long as the method takes the same input and returns the same stuff, you only have to edit your code in one place and you can be pretty confident that nothing is going to break.

      Now if you had written all that functionality procedurally, now you are talking about looking through pages of code trying to find every single customer select query that exists.

      Personally I write every single thing in PHP in classes. And I mean everything. The only thing that isn't in a class is a few lines in index.php that setup some constants, instantiate my framework class and call run(). Ever since I have started doing that life is bliss. Another advantage is that it is now terribly easy for me to reuse code, I just copy entire classes into new sites and reuse them.

        I've discovered classes recently and use it in my sites ever since. At this point I especially prefer to use it to do database stuff for me with simple lines in the main sources like $SQL->query("SELECT something FROM somewhere");

        Saves me the time to do mysql_connect,mysql_select_db and mysql_close all the time.
        Keeps my sources clean, which I like best.

          Can anyone recommend a really good, comprehensive source for information on working with classes?

            Another good one is Head First Design Patterns by oreilly press.

              6 days later

              Once I got my brain to think in OO, design patterns (Design Patterns Elements of Reusable Object-Oriented Software by Gamma et al) were extremely important to helping me actually write good OO code.

              I think many folks are mislead by promises of OOP not realizing the dangers that lie ahead. Bad OOP code is just as bad as bad functional or scriplet or whatever you normally write. I find that an OO solution about 10x-100x harder than a functional approach. If people would simply design their code in layers (presentation, domain, persistance (usu. D😎) they'd find that a functional approach works well. I use a blend...some OO but mostly functions.

                Write a Reply...