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
jurriemcflurrie
Forum Commoner
Posts: 61
Joined: Wed Jul 06, 2005 7:14 am
Location: Den Haag, the Netherlands

OOP....!

Post by jurriemcflurrie »

I've made several attempts to code with classes with php and I'm getting more used to it day by day. But as I code along I still can't find out the usefulness of it. I can't get an answer to it neither.

Why can't I just put several functions in a seperate file? Thats what you do with classes also, right?

I dunno if i'm missing something but I'm really missing the point of classes. Can someone tell me why I should continue to learn it. Else I'll just keep coding old style.

Thanks in advance
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

we're not going to reignite the flame-war so read this first: viewtopic.php?t=37995
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

I suggest researching Domain Model.
alvinphp
Forum Contributor
Posts: 380
Joined: Wed Sep 21, 2005 11:47 am

Post by alvinphp »

OOP is not a bunch of functions, it is a way of thinking about your application. I highly suggest getting Professional PHP5 from WROX as it gives a good explanation and understanding of OOP with PHP5.

For me personally, I could not code any other way.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Classes aren't just containers for functions. They bring data and the functions which act upon that data together in a single object. You end up with the application divided up into independent chunks rather than all tangled up in a big ball of spaghetti. It is possible to organise procedural code but encapsulation is a much more powerful tool. I look at coding entirely in the global scope as one dimensional, functions add a second, but using OOP is a more sophisticated 3D. No-one who has learned OOP properly would go back to procedural code.

Suppose you have a database class which wraps up native mysql functions. Now suppose you need to use a second, postgres db. If you create another postgres version of the database class with the same interface you can slot that into the code very easily (polymorphism). The database classes can be tested independently and re-used.

OOP takes a while to learn and you'll probably find that you have to tear up your ideas regularly. However, each time you'll be learning a little bit more and developing the analytical skills you need to write good objects which are loosely coupled and cohesive.

Part of the problem is, now that you've encapsulated code into classes, how do you get objects to talk to each other? You need to study design patterns to find out about common solutions to different types of problem - and you'll have to adapt these or create your own designs as necessary. Be careful not to over-use inheritance. This is a common pitfall for newcomers to OOP (I did that myself).
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post by Roja »

McGruff wrote:No-one who has learned OOP properly would go back to procedural code.
Now quit that. I was really happy that I was going to be able to agree with everything you said until this comment, making a generalized, inaccurate statement again.

Just explain the merits of OOP. It will sell itself. Don't worry about what people do or don't do in your opinion (especially when you've heard counter examples numerous times).
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

one hint of a flame and I lock this thread... no exceptions.... just fyi..
User avatar
jurriemcflurrie
Forum Commoner
Posts: 61
Joined: Wed Jul 06, 2005 7:14 am
Location: Den Haag, the Netherlands

Post by jurriemcflurrie »

First - thanks for the replies!

When I posted this thread I had no idea that it would <span style='color:blue' title='I'm naughty, are you naughty?'>smurf</span> some people off so much :P (no offence to anyone).

After reading the replies and links I came to the solution that it is all up to me. I'll have to determinate if I want to use classes or not. I didn't found an answer to that yet but I do know that I want to be able to use classes when I want to use them :)

For me my question is answered, thanks a lot to all. I'll start to study the links above again and search for more info about the topic. If anyone think that I should read / have a look at / try to program / whatever, I'll be glad to hear it!
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

If you're learning OOP maybe do a simple project - like a mini blog. You can cook up a simple blog quite quickly (its just an app that stores an article and displays a list of such articles). Its also small enough a code base to easily allow some experimentation with objects.

I'd avoid this on larger projects until you feel comfortable with objects.
User avatar
jurriemcflurrie
Forum Commoner
Posts: 61
Joined: Wed Jul 06, 2005 7:14 am
Location: Den Haag, the Netherlands

Post by jurriemcflurrie »

Ok I quickly made an authorisation script...

_inc/_auth.php:

Code: Select all

<?
	class auth {
		var $username;
		var $password;
		
		function login($username,$password) {
			if(!$this->check($username,$password)) {
				echo 'Login failed!';
			}
			else {
				$_SESSION[username]='$username';
				$_SESSION[password]='$password';
			}
		}
		
		function check($username,$password) {
			$check=mysql_query("
				SELECT *
				FROM auth_users
				WHERE
					username='$username' AND
					password='$password'
				LIMIT 0,1
			")or die(mysql_error());
			
			if(mysql_num_rows($check)==0) {
				return false;
			}
			else {
				return true;
			}
		}
		
		function logout() {
			$_SESSION[username]='';
			$_SESSION[password]='';
		}
	}
?>
index.php:

Code: Select all

<?
// Authenticate
	include('_inc/_auth.php');
	$auth = new auth;
	
	if(!$auth->check($_SESSION[username],$_SESSION[password])) {
		if($_GET[username] AND $_GET[password]) {
			$auth->login($_POST[username],$_POST[password]);
		}
	}
	else {
		// Show content	
	}
?>
Am I doing things right? Any comments would be appreciated :)

thanks
User avatar
wtf
Forum Contributor
Posts: 331
Joined: Thu Nov 03, 2005 5:27 pm

Post by wtf »

It's apparent that PHP is going OOP. At this point it may not be there but it'll have to if it want's to become an enterprise solution. At one point you'll just have to embrace it. Each new version will have features that you may not be able to use with procedural coding, for example exceptions in PHP 5.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

This suggestion is coming from someone who is not very experienced with OOP, so please do not take as gospel, but!

For that example, it might be worth bulilding the class so it can be used statically, instead of having to instantiate an object from it, as there isn't a 'real' reason to maintain an object (e.g. there aren't any properties!)

As it happens, for the most part, it already can be:

Code: Select all

<?php
// Authenticate
    include('_inc/_auth.php');

    if(!(isset($_POST['username'])) || !(isset($_POST['password]'))) {
        //login failed, do summat else    
    } elseif (auth::check($_POST['username'], $_POST['password'])) {
        //login sucessful
    } else {
        //login failed, do summat else    
    }
?>
Also - Structure your class so that it will filter, validate and escape the data that is being passed to it. And also structured so that it will return results, rather than explicity output them, this way you can manage the input/output of the objects and classes efficiently. In some circumstances you may want the message "Login failed" to be echo'ed, but in others you may want a different action to occur, such as redirecting to a login page, as an example. :)
Jeroen Oosterlaar
Forum Commoner
Posts: 37
Joined: Sun Nov 06, 2005 4:12 pm

Post by Jeroen Oosterlaar »

I totally understand the topic starter. It is rather funny really. I have written a lot of Java (web) applications and in Java I always felt comfortable writing my software using the OOP paradigm. When I started to use PHP to develop web solutions I was quite excited when I found out that it offers OOP, since I cleary see and have experienced (with Java) the advantages.

But for some reason I just cannot think fully OOP when developing in PHP. I cannot explain why this is, but just like jurriemcflurrie says: why not just use functions? Most business logic is only singe page related (such as inserting something in the database) so the use of objects doesn't make much sense when aiming at reusability and generalizability. Of course, general functionality such as checking for a valid login is very suitable for the OOP approach, but OOP is only true OOP when it is fully OOP.

So, why would I go the OOP way in PHP when there is not a single advantage in contrast to non-OOP? (At least in the case of certain projects.) In fact, using OOP only requires more files and file interlinking (includes), which only negatively influences the productivity and efficiency.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

Jenk wrote:as there isn't a 'real' reason to maintain an object
What about serializing the object into the session so the validation is saved and you dont have to re-check the password on each page view? Is that a 'real' enough reason?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

function login($username,$password) {
            if(!$this->check($username,$password)) {
                echo 'Login failed!';
            }
            else {
                $_SESSION[username]='$username';
                $_SESSION[password]='$password';
            }
        }
should be

Code: Select all

function login($username,$password) {
            if(!$this->check($username,$password)) {
                echo 'Login failed!';
            }
            else {
                $_SESSION['username'] = $username;
                $_SESSION['password'] = $password;
            }
        }

1) always quote your array indices
2) variables will not parse in single quotes
Post Reply