Forum Moderators: coopster

Message Too Old, No Replies

PHP the OOP way .

         

naiquevin

4:00 pm on May 14, 2009 (gmt 0)

10+ Year Member



I have been working with PHP & MySQL for past 3 months. Much of it has been learned referring to online tutorials as well as developing some simple applications simultaneously. I have just completed developing a social network kind of a thing.. (login/ signup / profiles and stuff.. ).All this while I have been using the procedural approach.

Now that I am quite comfortable with it, I am looking forward to start learning OOP in PHP. I found some basic tutorials online and after reading them, I could pretty much understand how it works.

But my question is -
what are the kind of applications in which OOP is justified? Because after going through the basics, I felt OO approach means more coding and much more complexity (may be since I am new to it!)

So from where should I start..?
Will it be a good idea to re-code the community website using OOP? and if yes, then how do I use classes in, say for eg. a login system?

Please help..

Thanks..

abidshahzad4u

6:33 pm on May 14, 2009 (gmt 0)

10+ Year Member



Yes you are right, OOP means more coding.

The main advantage of OOP is it's re usability. Also the code written in OOP is easy to maintain. Major part of the code is in separate classes (business logic layer) and page (presentation layer) have minimal code.

If site is not very complex or large then there is no need to convert it to OOP, if it is moving to OOP will help you in future for addition/upgradation/correction tasks.

vordmeister

7:17 pm on May 14, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



I stick with procedural coding, but have a rule that no piece of code should be repeated in more than one file. It gets to be a pain to change things if you duplicate code.

I use includes and functions for that. Perhaps that could be called object orientated - or do you really have to use classes to be cool?

My worry is how easily OOP could be misused. Like the developers who will have you download a million massive javascript and ajax files with every page. Really easy to just include a load of classes you aren't going to use.

naiquevin

2:57 pm on May 15, 2009 (gmt 0)

10+ Year Member



I use includes and functions for that. Perhaps that could be called object orientated - or do you really have to use classes to be cool?

Even I do the same thing..and would prefer procedural way but I feel OOP has many other advantages... the most important being that OOP practices are more or less common across various languages such as Ruby, Java which makes learning these languages easier in future (I have only read this, I am not familiar with Ruby, Java etc languages)

Can any one help me figure out a starting point?

Thanks

idfer

4:53 pm on May 15, 2009 (gmt 0)

10+ Year Member



Here's one way i use OOP to its advantage: i noticed that most of my forms go through the same basic steps: display initial form, validate, redisplay if there are user errors, save/submit. So i wrote a basic class for form processing:

class BaseForm {
var $requiredFields = array();
var $errors = array();

function processRequest() {
if(isset($_REQUEST['op_submit']))
$this->doSubmit();
else
$this->doStart();
}

function doStart() {
$userData = array();
$this->outputFormPage($userData);
}

function doSumbit() {
$this->loadInput($userData);
$rc = $this->validateInput($userData);
if($rc === false) {
$this->outputFormPage($userData);
return;
}
$rc = $this->submitInput($userData);
if($rc === false) {
$this->outputFormPage($userData);
return;
}

$this->outputSuccessPage($userData);
}

// Implement reasonable default actions for other methods
// e.g.:

function outputFormPage($userData) {
$this->outputPageStart();
if(!empty($this->errors)
$this->outputErrorMessages();
$this->outputForm($userData);
$this->outputPageEnd();
}

function outputSuccessPage($userData) {
$this->outputPageStart();
echo '<p>Thank you for your request blah blah</p>';
$this->outputPageEnd();
}

function validateInput($userData) {
foreach($this->requiredFields as $requiredField)) {
if(!isset($userData[$requiredField])
¦¦ empty($userData[$requiredField])) {
$this->errors[] = "You must enter a value for $requiredField";
return false;
}
}
return true;
}

}

Then for each individual form, i create a subclass and override the methods that matter for that form, e.g.

class EmailerForm extends BaseForm {
function EmailerForm() {
$this->requiredFields = array('emailaddress', 'subject', 'comment');
}

// No need to rewrite handleRequest, doStart, doSubmit,
// outputFormPage, outputSuccessPage etc.

function outputForm($userData) {
echo '<form...';
...
echo '</form>';
}

function validateInput($userData) {
$rc = parent::validateInput($userData);
if($rc === false)
return false;
if(!isValidEmailAddress($userData['emailaddress'])) {
$this->errors[] = 'Invalid email address';
return false;
}
return true;
}

function submitInput($userData) {
...
return true;
}
}

$form = new EmailerForm();
$form->handleRequest();

If you write BaseForm carefully, you can save yourself a lot of rewriting for all your real forms.

naiquevin

6:50 pm on May 16, 2009 (gmt 0)

10+ Year Member



hey thanks idfer, you got me thinking!

rob7591

10:43 pm on May 16, 2009 (gmt 0)

10+ Year Member



I use OOP for my eCommerce website.

Most people just use a premade one, but I coded mine and it works very well.

Two classes I use are:
$cart: stores the customer's items, calculates totals of everything, figures out shipping, etc.

$db: stores the database username/password and executes queries.

I think a $db class should be used on every (PHP/MySQL) website because it makes it very easy to handle queries.

I have a few functions on my db class:

$db->query($q[, $db]); runs a mysql query on the specified database (or the current one if it's not specified).
$db->changeDB($db); changes the database's current database.

Then I have a few functions that pretty much just execute queries that I use a lot.

The advantage to this is that I open the fewest possible amount of connections. The __construct function opens the connection and the __destruct function closes it. It takes a lot of mess out of my individual pages because instead of having:
mysql_connect(...);
mysql_select_db(...);
mysql_query(...);
mysql_close();

I just have:
$db->query(...);

Also, the class has a counter that increases every time the query function is called, which is helpful for optimizing and debug info.

That's all I could think of for now, but I've definitely found it easier to code individual pages after creating those two classes.