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

McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

jurriemcflurrie wrote: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).
No problem: it was nothing to do with you. We've frequently had problems in similar discussions. Please feel free to ask anything you want.

You don't have to use OOP to create a functional site. Anything can be made to work. A language like php covers a whole range of people from hobbyists to professional programmers working on enterprise-level apps. If you just want to put together a personal web site, a degree-level learning effort probably won't make sense. Nothing wrong with that: an easy to learn gateway language is a good thing since it enables many people to tackle something they otherwise might not have been able to do.

However, at the other end of the scale, if you're thinking about a career in programming, OOP and other modern, agile practices such as unit testing are essential. You won't be able to apply for some of the best jobs without a solid XP grounding and the OOP skills you learn in php will be transferrable to other languages which you might want to pick up. OOP makes applications much easier to maintain - particularly when combined with testing. This isn't apparent until you have had the experience of maintaining applications over the long term or of working in groups. There is no better way to manage a code base.

Note: I'm assuming that we're specifically talking about web apps: in other fields procedural coding may have its uses.

[note: I've edited this following BDKR's complaint]
Last edited by McGruff on Sat Nov 12, 2005 4:56 am, edited 3 times in total.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

jshpro2 wrote:
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?
no, because that class/example is using $_SESSION to store the login and password, and that you would still need to call upon the method login or check on every page, as the unserialisation will not automatically call upon them, and it is not the object that is storing the username/password..
User avatar
jurriemcflurrie
Forum Commoner
Posts: 61
Joined: Wed Jul 06, 2005 7:14 am
Location: Den Haag, the Netherlands

Post by jurriemcflurrie »

Jenk:
1. I think I understand what you're saying. I must only use classes to validate / change / whatever data? Doesn't this mean that I get more code on 'index.php' (like when adding diffirent access levels to users)? As this is something I want to avoid.
2. Do you have a reason to do

Code: Select all

auth::check()
instead of

Code: Select all

$auth = new auth;
$auth -> check()
Jeroen Oosterlaar:
Dutch also?

Jcart
I know. Thanks anyways :)


_________________
Edit
I didn't knew there was another page already so I missed 2 posts :)

McGruff
Yes I saw the discussions in other threads. Anyways, I'm gonna learn OOP no mather what, then I'll see what suits for me.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

jurriemcflurrie wrote:Jenk:
1. I think I understand what you're saying. I must only use classes to validate / change / whatever data? Doesn't this mean that I get more code on 'index.php' (like when adding diffirent access levels to users)? As this is something I want to avoid.
2. Do you have a reason to do

Code: Select all

auth::check()
instead of

Code: Select all

$auth = new auth;
$auth -> check()
Jeroen Oosterlaar:
Dutch also?

Jcart
I know. Thanks anyways :)


_________________
Edit
I didn't knew there was another page already so I missed 2 posts :)

McGruff
Yes I saw the discussions in other threads. Anyways, I'm gonna learn OOP no mather what, then I'll see what suits for me.
The only reason I have suggessted auth::check() instead of $auth->check() is because your class auth does not have any properties (no variables within the class) so there isn't much point in instantiating an object from that class. Purely for efficiency.

If, however, you were to add methods (internal functions) or properties that perform tasks such as user level, then using an object will be necessary, rather than calling upon the class method statically.

Something like this will require an object to be instantiated:

Code: Select all

<?php
class auth 
{
	var $username;
	var $password;
	var $userlevel;
	
	function login($username,$password) 
	{
		if(!$this->check($username,$password)) {
			echo 'Login failed!';
		}
		else {
			$this->username='$username';
			$this->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) < 1) {
			return false;
		} else {
			/* USER LEVEL */
			$row = mysql_fetch_assoc($check);
			$this->userlevel = $row['userlevel'];
			return true;
		}
	}
	
	function getUserLevel() 
	{
		return $this->userlevel;
	}
	
	function logout() 
	{
		$this->username = NULL;
		$this->password = NULL;
	}
}
?>
Even though in your previous example, you had declared some internal variables (properties), you didn't use them :)

Now, when you want to transfer that object to a different page, you can do something like the following:

Code: Select all

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

$user = new auth();

$user->login($username, $pwd);

$_SESSION['object'] = serialize($user);

?>
Then on a following page:

Code: Select all

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

$user = unserialize($_SESSION['object']);

echo $user->getUserLevel(); //will echo whatever userlevel was determined from the query on the first page

?>
User avatar
jurriemcflurrie
Forum Commoner
Posts: 61
Joined: Wed Jul 06, 2005 7:14 am
Location: Den Haag, the Netherlands

Post by jurriemcflurrie »

I see. At least now it's clear when I should or should not start with those 'var $bla' things ;)

Jenk, your example was very usefull for me. Again I understand OOP a lot more. But I find it very hard to think - lets say - 'the OOP way'. I'll now start at as Maugrim_The_Reaper suggested a weblog. Witch gave me already a lot new problems as I don't know where to start anymore :P

Damn I hate OOP :lol:

_________________
Edit:
Forgot something to ask. I see you using serialize. I understand what it's doing (sort of) but why not run the script all over again, couse it seems to me that that will be a lot safer. Or am I missing something again?
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

Coming from java you may have come across Design Patterns - It takes a bit of reading first, but they offer a few starting points. The simplest is Page Controller. You initiate request to a php file, say index.php, which does whatever is required to display the index page. Since its a blog (presumably following my suggestion) its basically a db call (to collect some entries), and inserting these into a html template (see Savant2 or Smarty). The DB calls could be handled by some data access object (simply an object containing your SQL calls, e.g. getBlogEntries()), html templates by Savant2/Smarty (there are many other template engines), and... well that's it really - it's a start.

You can elaborate on this a great deal - i've left out security, more complex patterns (front controller for example), etc. But you get the point. Keep it simple at the beginning until you get a handle on it.

[quote=McGruff]We've frequently had problems with anti-OOP trolls in similar discussions.[/quote]

I don't see the topic being locked ;). I'll simply note Roja is definitely not anti-OOP. He's just not anti-Procedural either...:) I suppose I get labelled a "bad monkey" too? hehehe
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

jurriemcflurrie wrote: Edit:
Forgot something to ask. I see you using serialize. I understand what it's doing (sort of) but why not run the script all over again, couse it seems to me that that will be a lot safer. Or am I missing something again?
serialize() will keep the data stored in the objects properties, in that example, userlevel. :)

Running the script again would mean lots of repetition, thus less will be less efficient :)
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Jenk wrote:serialize() will keep the data stored in the objects properties, in that example, userlevel. :)

Running the script again would mean lots of repetition, thus less will be less efficient :)
Passing serialzed objects through sessions *can be* detremental to efficiency dependant on the size of the object, other data being stored in the session and of course your code base which would be required to re(build/construct) the object. I don't think it's fair to say that *it will* be less efficient, I think it's truer to say it *can be* less efficient.

I have noted previously that there can be quite a performance hit when passing large amounts of data through sessions. It may be fine for small applications, but I'm not sure it would do much for scalability?
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

No, you are quite right.

the problem with vast amounts of $_SESSION data, is $_SESSION itself is serialize()d between page requests and kept in flat files (location specified by the session.save_path directive)

If the objects are huge, it could be worth storing in the DB.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Note: some posts have been moved here. Often coding questions which touch on the OOP v procedural issue go off topic and the original poster is caught in the crossfire.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

When you said
Jenk wrote:as there isn't a 'real' reason to maintain an object
I must have misunderstood you. I thought you meant there is no reason to maintain any user authentication object, not the one being discussed in particular.
Jenk wrote:no, because that class/example is using $_SESSION to store the login and password, and that you would still need to call upon the method login or check on every page, as the unserialisation will not automatically call upon them, and it is not the object that is storing the username/password..
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

:)
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 think I get it... At least, the basics then :) I'll keep you all informed.

thanks a lot :)
User avatar
AKA Panama Jack
Forum Regular
Posts: 878
Joined: Mon Nov 14, 2005 4:21 pm

Re: OOP....!

Post by AKA Panama Jack »

jurriemcflurrie wrote: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
The best way to think about Classes would be as self contained code modules.

Here is a code example (yes very simple but effective example):

Code: Select all

class test{
	var $stuff = 0;
	function display()
	{
		echo $this->stuff;
	}
}

$obj1 = new test;
$obj2 = new test;

$obj1->stuff = "This One";
$obj2->stuff = 12134;

echo "1: ";
$obj1->display();
echo "<br>2: ";
$obj2->display();
With the above example you have two instances of the same class but the data stored in each instance is different. You can call $obj1->display() over and over and receive the same data every time, even if you call $obj2->display() at anytime. You will also notice that all variables in a class can be used by every function in said class. The use of the global tag isn't needed inside the various functions like they are needed for functions outside classes.

Code: Select all

function display()
{
	global $stuff;
	echo $stuff;
}
If the display function wasn't in a class you would have to populate the $stuff variable from another variable every time you want to execute the display function.

Code: Select all

$stuff = $stored1;
display();
echo "<br>2: ";
$stuff = $stored2;
display();
Using classes can make managing your variable structures alot easier in some instances. With that said classes are not the end all for PHP. Classes and Procedural each have there own uses depending upon the situation and one isn't necessarily better than the other. In many cases using precedural programming methods are faster than using classes. One of the problems with classes in PHP is memory usage and speed. Classes in PHP can create a large overhead in memory if the programmer isn't careful in how they impliment the usage of classes. Coupled with this is how classes can slow down the number of pages per second that can be processed by the server. Now I am not talking in how fast the functions inside the classes can execute but how fast an object is created for a class. The size of the class, number of extentions and number of classes all affect how many pages per second can be processed. With PHP 4 and even with PHP 5 a class heavy web page is going to be heavily impacted where a similar web page that minimally uses classes will process more pages per second.

For PHP the use of classes is fantastic for creating self-contained modules that can easily be transported between different projects. It reduces the amount of duplication and rewriting of code. But creating an entire web site using only classes will end up being more of a load on the server than one that uses procedural programming or a combination of procedural and classes for most of the site.

Bottom line with PHP is how the usage of classes and procedural program go hand-in-hand together. They both assist each other and you should use both methods if you want the most out of PHP.
User avatar
trukfixer
Forum Contributor
Posts: 174
Joined: Fri May 21, 2004 3:14 pm
Location: Miami, Florida, USA

Post by trukfixer »

So very well put! :) I have to agree 100%. the concept is essentially the same in almost any language .. Python, perl, C.. Basically the programmer needs to pay attention to the big picture.. the larger the project, the more important the procedural Vs. OOP debate comes into play... but it's largely up to the programmer to make the judgement call to optimize his/her application for top performance.
Post Reply