Why and When to use OOP?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

User avatar
Skoalbasher
Forum Contributor
Posts: 147
Joined: Thu Feb 07, 2008 8:09 pm

Why and When to use OOP?

Post by Skoalbasher »

I understand OOP and how to use it. I just don't know why I would use it.

Procedural seems to do the trick for me. I've been to the PHP manual, but it just tells me more of how to use OOP, and not why or when. If anybody could point me in the right direction that'd be awesome.

I seem to be able to get everything I need to get done with functions. And if I need to use them again, I do. Just save them and include them. Classes in PHP you still have to recreate every page you go to (right?), so.. what's the point?
mickeyunderscore
Forum Contributor
Posts: 129
Joined: Sat Jan 31, 2009 9:00 am
Location: UK

Re: Why and When to use OOP?

Post by mickeyunderscore »

I see what you mean, and yes at the end of execution all instantiated objects are lost and must be re-instantiated on the next request unless you serialize them into a cookie or something.

Excessive conditionals can point to the need for a polymorphic inheritance heirarchy to break down the logic and functionality. This way you can take the conditionals out of your main program and let the classes handle this themselves.

Tight coupling within your system, that is a change in one function/page requiring a change to several more can be avoided with OO. OO encourages decoupling so you can alter a single class or set of classes without breaking the system.

An unclear interface to a set of functions could be avoided by the use of a class/set of classes. You can keep the interface clear and defined, meaning any one can easily look at your class and see which functions they need to call to get the job done.

It's also down to personal preference and what exactly you are coding, I don't tend to code in a strictly OO fashion as some of the things I code aren't overly demanding and I find it easier and faster not to use OO. But for some functionality I find it better to use just OO as it can help simplify a complex problem.

If you like procedural and are happy with the results then there isn't really a need to change over.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Why and When to use OOP?

Post by josh »

mickeyunderscore wrote:If you like procedural and are happy with the results then there isn't really a need to change over.
That's like saying if you're happing eating nothing but water and bread there's no need to try anything else. Until you try it how do you know? The biggest thing objects did for me when I started is when I had more than 1 instance of an object. The procedural way would be maintain my data outside of the business logic, like an array, iterate that array, call functions on it, reassign data to the array, etc.. then Id copy and paste that if I had to use it somehwere else..

Objects change that because once you write the object once you can have it instantiated 10000 different times with different data in each object. PHP has to parse procedural code on every request as well so your other argument is kinda meaningless
User avatar
Skoalbasher
Forum Contributor
Posts: 147
Joined: Thu Feb 07, 2008 8:09 pm

Re: Why and When to use OOP?

Post by Skoalbasher »

Thanks for the replies! I'm still not really understanding where to do it. I'm trying to find examples, and they're all about making squares and crap. I really could care less if I can make a blue or red square/rectangle.

Let's take a user login page. Since there's only one user logged in at a time, i'm not going to have multiple object instances. I'm working on a page right now that keeps track of animal records. Shots, cleaning, feeding, pooping, etc... would OOP do me good here?
jshpro2 wrote:PHP has to parse procedural code on every request as well so your other argument is kinda meaningless
Right I understand this, that's why I don't understand what the big deal about classes in PHP are. I've read a few examples and they totally make sense, but like I stated above.. I've yet to see a practical example in PHP.

I hope it doesn't sound like I'm arguing here. Just trying to learn and figure out what I need to do to code PHP better, cleaner, faster.

Like, I have an include file functions_users and it has all theuser functions. Including one you call, it passes back an array with all the data from that row in MySQL. i'm not sure where I was going with this..
mickeyunderscore
Forum Contributor
Posts: 129
Joined: Sat Jan 31, 2009 9:00 am
Location: UK

Re: Why and When to use OOP?

Post by mickeyunderscore »

That's like saying if you're happing eating nothing but water and bread there's no need to try anything else. Until you try it how do you know?
Well TBH I've never been taught to program in a procedural style, on my course they taught only OO from the start (Java), so I didn't really like to put the procedural style down or say it's bad. But from what I've seen, I would compare procedural to bread and water in most cases, as you say.

OO PHP isn't supposed to be about persistence, all PHP scripts lose all data when they finish running. OO is more about how you manage a problem, instead of a sequential list of function calls and logic tests (as I understand procedural to be), the logic and data handling falls to the classes more.
Theory?
Forum Contributor
Posts: 138
Joined: Wed Apr 11, 2007 10:43 am

Re: Why and When to use OOP?

Post by Theory? »

It took me forever and a day to wrap my head around OOP and once I got it, I was amazed I didn't before. It's sort of about expectations. The greatest part, to me at least, about OOP is that you can think about smaller components of your system. Instead of thinking of pages in sequence:

loginForm.php
login.php
loggedIn.php
logOut.php

You can think in terms of entities and relations, or actors and actions, or whatever the hell you want to call them. So now you start thinking of:

class User
Which represents the actual user trying to gain access to whatever

class Auth
The class that checks the properties of the User object against the DB records (this is excluding the DB object that you'd probably want to have) and returns either a cookie/session or tells them they didn't provide the proper credentials. In this instance I'm also excluding a hypothetical wrapper class for the Session itself which some people like to do.

class Acl
The class that matches the authorized credentials to the resources being requested, like a moderator requesting access to the admin page or something of that nature.

OOP, IMHO, is a much smarter and far more modular way of looking at programs. It also makes it so much easier to refactor a program down the line because you end up having to change far less code in order to improve the whole system.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Why and When to use OOP?

Post by josh »

Skoalbasher wrote:I hope it doesn't sound like I'm arguing here.
No not at all, you are asking questions which is necessary to learn. If you feel the urge to challenge something then challenge it, its part of the enlightenment process :D By challenge it I mean try for yourself and see wether or not we know what we're talking about, what works best for you works best for you.
Just trying to learn and figure out what I need to do to code PHP better, cleaner, faster...
Right, a practical example is lets say you had user accounts, and lets say you had to format the date. With procedural code lets say you had the date as a timestamp in the databse, so youd query the database, iterate the rows, and call functions on each piece of data that needed to be formatted, like the date function, etc...

If you were smart you'd take the whole above procedural code and move it into a function. But lets say you wanted to change the format that date displays with, well with functions you could parametrize your function so each time you call it you pass it options on how it should perform its calculations.

Now lets look at the same thing from an OO perspective. You'd start out with a collection of row objects. Youd iterate these rows and you'd call $row->getDate() on each object for example. Each object is an instance of a class you wrote that has a getDate method. inside the method you access the data for each row with $this->nameOfProperty.

So one class, infinite objects which model infinite # of "real world" objects. Lets say instead of rows you had a collection of "animals" ( I know stupid eg. ), animals would be what we can an abstract class. It might define a method noise(), and then you might have other classes that subclass the animal class and override the noise() method. Dogs would override it and bark, humans would override it and speak, etc.. So later on in your program if you knew you had a collection of animals you could iterate them and call $animal->noise() on each one, and each one would do it's own thing. Much cleaner then if() and switch() in my opinion. I recommend a book called head first java. Its about java not PHP but you'll have no problem understanding it.
User avatar
Skoalbasher
Forum Contributor
Posts: 147
Joined: Thu Feb 07, 2008 8:09 pm

Re: Why and When to use OOP?

Post by Skoalbasher »

jshpro2 wrote:
Skoalbasher wrote:If you were smart you'd take the whole above procedural code and move it into a function. But lets say you wanted to change the format that date displays with, well with functions you could parametrize your function so each time you call it you pass it options on how it should perform its calculations.

Now lets look at the same thing from an OO perspective. You'd start out with a collection of row objects. Youd iterate these rows and you'd call $row->getDate() on each object for example. Each object is an instance of a class you wrote that has a getDate method. inside the method you access the data for each row with $this->nameOfProperty.

So one class, infinite objects which model infinite # of "real world" objects. Lets say instead of rows you had a collection of "animals" ( I know stupid eg. ), animals would be what we can an abstract class. It might define a method noise(), and then you might have other classes that subclass the animal class and override the noise() method. Dogs would override it and bark, humans would override it and speak, etc.. So later on in your program if you knew you had a collection of animals you could iterate them and call $animal->noise() on each one, and each one would do it's own thing. Much cleaner then if() and switch() in my opinion. I recommend a book called head first java. Its about java not PHP but you'll have no problem understanding it.
Ohh, that actually makes some sense there! Yes! Getting somwhere! So something like this?

Code: Select all

 
$dog = new Animal();
$dog-> noise = "bark";
 
echo $dog-> noise;
 
Something like that? I'm trying to understand it all. Maybe I don't know classes like I thought. Just remember some from C++ 1.

I do put most of my stuff into functions. Your saying though like, have a class Animals, and when create a new animal, send the animal type, ie dog, cat etc.. then the class would pull everything it needs and put it into an array of some sort? Then if I wanted a different animal, just call it and use a different animal? So it's pulling a lot from DBs?
Theory?
Forum Contributor
Posts: 138
Joined: Wed Apr 11, 2007 10:43 am

Re: Why and When to use OOP?

Post by Theory? »

Skoalbasher wrote:
jshpro2 wrote:
Skoalbasher wrote:If you were smart you'd take the whole above procedural code and move it into a function. But lets say you wanted to change the format that date displays with, well with functions you could parametrize your function so each time you call it you pass it options on how it should perform its calculations.

Now lets look at the same thing from an OO perspective. You'd start out with a collection of row objects. Youd iterate these rows and you'd call $row->getDate() on each object for example. Each object is an instance of a class you wrote that has a getDate method. inside the method you access the data for each row with $this->nameOfProperty.

So one class, infinite objects which model infinite # of "real world" objects. Lets say instead of rows you had a collection of "animals" ( I know stupid eg. ), animals would be what we can an abstract class. It might define a method noise(), and then you might have other classes that subclass the animal class and override the noise() method. Dogs would override it and bark, humans would override it and speak, etc.. So later on in your program if you knew you had a collection of animals you could iterate them and call $animal->noise() on each one, and each one would do it's own thing. Much cleaner then if() and switch() in my opinion. I recommend a book called head first java. Its about java not PHP but you'll have no problem understanding it.
Ohh, that actually makes some sense there! Yes! Getting somwhere! So something like this?

Code: Select all

 
$dog = new Animal();
$dog-> noise = "bark";
 
echo $dog-> noise;
 
Something like that? I'm trying to understand it all. Maybe I don't know classes like I thought. Just remember some from C++ 1.

I do put most of my stuff into functions. Your saying though like, have a class Animals, and when create a new animal, send the animal type, ie dog, cat etc.. then the class would pull everything it needs and put it into an array of some sort? Then if I wanted a different animal, just call it and use a different animal? So it's pulling a lot from DBs?
Sort of. You definitely have the concept down. I would say, in terms of best practices, you'd probably want to set the noise using a method instead of altering the noise member directly, but in terms of concepts you have the general idea.
mickeyunderscore
Forum Contributor
Posts: 129
Joined: Sat Jan 31, 2009 9:00 am
Location: UK

Re: Why and When to use OOP?

Post by mickeyunderscore »

I think jshpro2 was thinking more along the lines of a set of classes extending from an abstract class Animal() which contains the common function noise(), e.g.

Code: Select all

abstract class Animal{
    protected $noise;
 
    public function noise(){
        echo $this->noise;
    }
}
class Dog extends Animal{
 
    public function __construct(){
        $this->noise = 'woof';
    }
}
class Human extends Animal{
 
    public function __construct(){
        $this->noise = 'Hello, sir';
    }
}
User avatar
Skoalbasher
Forum Contributor
Posts: 147
Joined: Thu Feb 07, 2008 8:09 pm

Re: Why and When to use OOP?

Post by Skoalbasher »

Theory? wrote: Sort of. You definitely have the concept down. I would say, in terms of best practices, you'd probably want to set the noise using a method instead of altering the noise member directly, but in terms of concepts you have the general idea.
Thanks. I really am trying to wrap my head around this. Sometimes it's a lot of info and I kinda feel like saying F-It and throwing my keyboard across my office, but I'm going to push through. At first I felt I had it, then I went and looked at examples. I see that I do this stuff procedurally and it's WAAAY easier. Makes more sense to me.

I know I'm getting help here from you guys, but I really haven't been more annoyed in my entire life I don't think. I really have to understand this because I'm trying to get a new job, and they use a lot of it. I know if I can get it.. there's going to be something that just snaps and I'll understand it. Maybe if you guys don't mind I can post some stuff up that I have and someone can help me convert it to OO?
User avatar
Skoalbasher
Forum Contributor
Posts: 147
Joined: Thu Feb 07, 2008 8:09 pm

Re: Why and When to use OOP?

Post by Skoalbasher »

mickeyunderscore wrote:I think jshpro2 was thinking more along the lines of a set of classes extending from an abstract class Animal() which contains the common function noise(), e.g.

Code: Select all

abstract class Animal{
    protected $noise;
 
    public function noise(){
        echo $this->noise;
    }
}
class Dog extends Animal{
 
    public function __construct(){
        $this->noise = 'woof';
    }
}
class Human extends Animal{
 
    public function __construct(){
        $this->noise = 'Hello, sir';
    }
}
So how would I use this in the actual code though?

Code: Select all

 
// like this?
$dog = new Animal(Dog);
 
I really am sorry if I'm being difficult.. lol.
mickeyunderscore
Forum Contributor
Posts: 129
Joined: Sat Jan 31, 2009 9:00 am
Location: UK

Re: Why and When to use OOP?

Post by mickeyunderscore »

It depends how you want to use it. At the moment you have to instantiate the classes yourself:

Code: Select all

$h = new Human();
$d = new Dog();
But if you wanted you could restrict access to the children by declaring a protected constructor and force access through the animal class:

Code: Select all

abstract class Animal{
    
    protected function __construct(){}
 
    public static function get(){        
        $r = rand(1,2);
        if($r==1){
            return new Dog();
        }elseif($r==2){
            return new Human();
        }
    }
 
    abstract public function noise();
}
class Dog extends Animal{
 
    public function noise(){
        echo "woof";
    }
}
class Human extends Animal{
 
    public function noise(){
        echo "Hello";
    }
}
 
$something = Animal::get();
$something->noise();
In that example Animal will return a random child class, both children override noise() with their own functionality.

I like this kind of functionality, where the actual object is determined at runtime, as all the decision making relating to that set of classes is contained exclusively within the classes themselves rather than in your main program.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Why and When to use OOP?

Post by josh »

I really recommend the head first java book. Itll learn ya' the OO concepts in a semi formal manor but uses down to earth examples, I used the animal - dog inheritance example cuz its one I specifically remembered when I read a year or 2 ago
User avatar
Skoalbasher
Forum Contributor
Posts: 147
Joined: Thu Feb 07, 2008 8:09 pm

Re: Why and When to use OOP?

Post by Skoalbasher »

jshpro2 wrote:I really recommend the head first java book. Itll learn ya' the OO concepts in a semi formal manor but uses down to earth examples, I used the animal - dog inheritance example cuz its one I specifically remembered when I read a year or 2 ago
That's what it's called? Head First? I'll give it a shot, maybe pick it up this weekend. It's odd, because I'm actually working on something with animals, so that kinda helps actually. lol.
Post Reply