Click to See Complete Forum and Search --> : First pop @ OOP


jonno946
11-28-2004, 07:22 AM
hi there,

been readin loads of tutorials over the past couple of days trying to et my head round OOP :o

anyway... this is my first oop based script, its pretty damn basic but just wondering whether i'm goin along the right lines?

any suggestions etc... ?

It validates usernames/passwors/email addresses so far :)

thanks :D


<?php

class mysql {

// database connection class

var $connection, $username, $password, $host, $database;

function mysql() {

$this->username = "dbusername";
$this->password = "dbpassword";
$this->host = "localhost";
$this->database = "dbname";

}

function db_connect() {

$this->connection = mysql_connect($this->host, $this->username, $this->password);

if(!$this->connection) {

die("<b>Error establishing connection to database:</b> " . mysql_error());

}

$select_db = mysql_select_db($this->database, $this->connection);

if(!$select_db) {

die("<b>Error establishing connection to database:</b> " . mysql_error());

}

}

function db_disconnect() {

$disconnect = mysql_close($this->connection);

}



}

class validate_registration {

// this class validates the 3 main registration variables, username, password and email.

var $username, $password, $password2, $email, $email2, $connection, $error_array = array();

function validate_username() {

// check max username length

if(strlen($this->username) > 15) {

array_push($this->error_array, "Chosen username exedes 15 character maximum limit.");

}

// check min username length

if(strlen($this->username) < 3) {

array_push($this->error_array, "Chosen username does not meet 3 character minimum limit.");

}

// check username doesn't exist

$query_db = @mysql_query("SELECT count(userid) from users WHERE username = '" . addslashes($this->username) . "'", $this->connection) or die ("<b>MySQL Error:</b> " . mysql_error());

if(mysql_result($query_db, 0) != 0) {

// username already in use

array_push($this->error_array, "Chosen username is already in use by another member.");

}

// check for illegal characters

if(!preg_match("/^[-_a-zA-Z0-9]+$/", $this->username)) {

array_push($this->error_array, "Username contains invalid characters.");

}

}

function validate_password() {

// check passwords match

if($this->password != $this->password2) {

array_push($this->error_array, "Your passwords do not match.");

}

// check max password length

if(strlen($this->password) > 32) {

array_push($this->error_array, "Chosen password exedes 32 character maximum limit.");

}

// check min password length

if(strlen($this->password) < 6) {

array_push($this->error_array, "Chosen password does not meet 6 character minimum limit.");

}

}

function validate_email() {

// check emails match

if($this->email != $this->email2) {

array_push($this->error_array, "Your emails do not match.");

}

// check email validity

if (!preg_match("/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\.)+([0-9A-Z]){2,4}$/i", $this->email)) {

array_push($this->error_array, "Your email is formatted incorrectly.");

}

// check max password length

if(strlen($this->email) > 50) {

array_push($this->error_array, "Chosen email exedes 50 character maximum limit.");

}


// check min password length

if(strlen($this->email) < 6) {

array_push($this->error_array, "Chosen email does not meet 6 character minimum limit.");

}

}

function display_errors() {

$number_of_errors = count($this->error_array);

if($number_of_errors < 1) {

return TRUE;

}

$key = 1;

echo "Validation found <b>" . $number_of_errors . "</b> input error(s):<br><br>\n";

foreach ($this->error_array as $error) {

echo $key . ". " . $error . "<br>\n";

$key++;

}

}


}

// instantiate db connection object

$database = new mysql;

// instantiate validation object

$validation = new validate_registration;



// connect to database

$database->db_connect();



// register object variables

$validation->username = "myusername";

$validation->password = "123456";

$validation->password2 = "123456";

$validation->email = "test5@test.com";

$validation->email2 = "test5@test.com";



// register db connection variable

$validation->connection = $database->connection;



// validate

$validate_username = $validation->validate_username();

$validate_password = $validation->validate_password();

$validate_email = $validation->validate_email();



// display result of validation

if($validation->display_errors() == TRUE) {

echo "Passed validation. Register code here.";

}



// disconnect from database

$database->db_disconnect();



// kill off objects

unset($database);

unset($validation);

?>

jonno946
12-01-2004, 10:17 AM
* yawn *

30 views and no replies :p

onion2k
12-01-2004, 10:31 AM
We're all in awe of your ability.

jonno946
12-01-2004, 11:00 AM
huh whats is that supposed 2 mean?

:rolleyes:

RossC0
12-01-2004, 11:20 AM
You sure have posted alot for someone who is new to OOP in php! ;)

Anyway looks good so far!

jonno946
12-01-2004, 11:38 AM
ahh thanks for that

makes lots of sense :)

Jonno

edit: why has my post come before yours lol

RossC0
12-01-2004, 11:51 AM
well OOP is all 'horses for courses' and yes you can have a set of functions that do the same thing, it all depends on personal preference.


It is important to stress that one of the core ideas behind OOP is that code written by the programmer is placed in reusable chunks. Reusable chunks of code save the developer time and money during the coding process, as well as making the code much more efficient. These reusable chunks of code are then used to create what we call an object; the object can be manipulated, made to do things, etc.


So in the end its all about creating clean reusable code. The class structure helps keep logic separate whilst being easily accessable.

You can certainly extend the user class - to include registration validation, and user page permissions, user prefrences etc...

But at the end of the day its all down to coding styles and prefence.

anm
12-13-2004, 10:51 AM
Yikers! What tutorials did you use? I've been trying to get my head around OOP in PHP and haven't been able to. . .still stuck just doing plain old functions!!

jonno946
12-13-2004, 12:42 PM
i started by reading this on phpfreaks:

http://www.phpfreaks.com/tutorials/48/0.php

then googled and found this:

http://www.liquidpulse.net/articles/php/oop/php_object_oriented_programming/introduction

then read the seaction in the php manual:

http://www.php.net/oop

plus a couple more on the way...

the hardest thing for me was trying to grasp the advantages between using classes/oop over just normal functions.

:)

anm
12-14-2004, 12:08 PM
Thanks! I'm currently in the act of writing a class for secure page generation from GET variables. . .but I'm not really clear on classes and OOP so this will help. . .

Larry Bigner
01-15-2005, 03:12 AM
Good job on your first OO.

Here are some tips to remember:

1. Define important things outside of the class at the top of the page or in a config file.

Ex: define( "TABLE_PREFIX", "db_" );
define( "DIR_PATH", dirname(__FILE__) );

2. Always return, not echo.

Ex: return $this->num_rows;
return $ret;

3. Try to comment every single function. Keep in mind that a good class will be easy to read for almost anyone.

Ex: /* This is a tricky part, don't change unless you have a deep understanding of blah */

4. Make default variables, not unmodifiable values.

Ex: var $default_limit = 15;

5. Seperate classes into files, and make sure to put them all in a directory by theirself.

Ex: All re-useable classes go into includes\lib\, and all page-specific classes go into includes\.

That should help you to create good re-useable classes that not only you, but other people can use.

jonno946
01-18-2005, 05:56 AM
thanks for your feedback larry - i found it most useful :)

Jonno

Norman Graham
01-18-2005, 08:10 AM
Hi Jonno

Which version of PHP you using? I'm setting up LAMP with PHP5 at the moment and want to adopt an OOP approach right from the start. I've been doing mostly procedural code with PHP4 and WAMP for a few years now.

I understand that PHP5 is now (almost) fully OO-capable, but I don't know what the implications of that are for existing PHP4 OO-code.

All the best

Norm

jonno946
01-18-2005, 07:05 PM
Hi norman,

currently running WAMP with PHP 5.01, however my code above would work on earlier versions.

i've been playing around with PHP 5 OO, which did seem abit more complex (php is my first programming language appart from a bit of vb a couple of years back), but the more i learn the more i can see an improvement on php 4 OO.

:)

Jonno

Larry Bigner
01-20-2005, 10:44 PM
PHP5 is like a godsend of improvements for PHP.

It not only improves upon OO programming, but it also adds a much-needed Exception handling.

Error-handling prior to this resulted in ugly error messages being echoed to the screen without the users knowledge of what they meant.

Now, you can write Try&Catch methods for errors.

My host has no updated to PHP5 yet though, so I have yet to try it out.

Weedpacket
01-21-2005, 12:23 AM
Originally posted by Larry Bigner
Error-handling prior to this resulted in ugly error messages being echoed to the screen without the users knowledge of what they meant.You know you're supposed to turn those off for production code, right? Log 'em elsewhere and write something more friendly?

planetsim
01-21-2005, 03:14 AM
so something like those oh your the 10,000,000th person you win a prize :p, or isnt that friendly enough.

Weedpacket
01-21-2005, 04:28 AM
Originally posted by planetsim
so something like those oh your the 10,000,000th person you win a prize :p, or isnt that friendly enough. YOU MAY ALREADY HAVE WON!!!
I can't say for sure, though, because the database has gone belly up....Sorry.