Jump to content

Help with Registration Class


TomTees

Recommended Posts

This is related to my post http://www.phpfreaks.com/forums/index.php/topic,307907.msg1455208.html#msg1455208

 

I have never programmed using OOP, and I am unsure where to start.

 

All of the tutorials and books I have read use stupid examples that don't seem to help you "in the real world"?!  >:(

 

So I want to write my first bit of PHP OOP to register Customers for my website.

 

I think having a "Registration" class makes sense, but I'm not sure how to tie that to my website.

 

If I write an HTML webpage and on it I have a Form where users can enter registration info, then how do I tie that "static" and/or "procedural" code to my OOP?

 

I was thinking of having it so that when a user clicks the "Register" button that I call a PHP file that has my Registration class and I first instantiate it so that the user has his/her own "Registration object".

 

From there, maybe I could call a method in Registration that actually registers the user.  (Or maybe I can just do that during instantiation?!)

 

Can someone help me out here?

 

 

TomTees

 

Link to comment
Share on other sites

php oop is worthless for this type of thing, php classes for this type of precedure is basically to make this code includeable into multiple files..

 

php oop is GOOD for creating multiple instances and have them independant of the other instances..

 

for this purpose classes aren't going to give you an "oop" feel, it will give you a function feel with a nifty wrapper..

Link to comment
Share on other sites

Eh, a Registration class could be useful if you need to do things above and beyond simply obtaining form info and stuffing it in a database.  Things like logging, counting registrations, and creating end user objects that interact with the site.

 

To the OP: you should really sit down and plan your site.  Adding a class 'just because' isn't beneficial, and isn't really a good way to learn as you'll simply wind up writing procedural code wrapped in a class.  The power of OOP comes from objects interacting with one another.

Link to comment
Share on other sites

php oop is worthless for this type of thing, php classes for this type of precedure is basically to make this code includeable into multiple files..

 

php oop is GOOD for creating multiple instances and have them independant of the other instances..

 

for this purpose classes aren't going to give you an "oop" feel, it will give you a function feel with a nifty wrapper..

 

So how would you recommend I approach things so I do get a real "OOP feel"??

 

 

TomTees

 

 

Link to comment
Share on other sites

Eh, a Registration class could be useful if you need to do things above and beyond simply obtaining form info and stuffing it in a database.  Things like logging, counting registrations, and creating end user objects that interact with the site.

 

To the OP: you should really sit down and plan your site.  Adding a class 'just because' isn't beneficial, and isn't really a good way to learn as you'll simply wind up writing procedural code wrapped in a class.  The power of OOP comes from objects interacting with one another.

 

I'm not sure I follow...

 

I have done A LOT of planning.  However I'm new to OOA/OOD/OOP and need help with the OO part.

 

I sketched out how the main parts of the website should look and I have written Use-Cases for the main parts as well.  I also have created an ERD for the backend.

 

The whole thing I'm stuck on is figuring out what are good Classes so I can do OOP.

 

And I do NOT want to write procedural code wrapped in Classes.

 

So if you can help I'd appreciate it!

 

 

 

TomTees

 

 

Link to comment
Share on other sites

Objects tend to work well when you can think of them as a unit of something. They can be concrete, like a record in a database, a group of records in some sort of list or table, or more abstract, like a template.

 

The over-arching principle that applies in every case is that an object will do different things depending on how it was set up - as in what properties it has. This allows your scripts that interact with the objects to be written without needing any knowledge of how the object works - it can simply create the object with the correct data, and then tell the object to do something (i.e. call it's methods).

 

The benefit to you as the developer is that your code is easy to read, and you can separate out the logic into the classes, where it can be reused (or debugged) more easily and extensibly.

 

In this case, I would recommend doing things from the perspective of a 'User' class. In the script that processes your registration form, you could treat your User like so:

 

$user = new User();

$data = array('first_name'=>$_POST['first_name'], 'last_name'=>'$_POST['last_name'], 'email'=>$_POST['email'], 'password'=>md5($_POST['password']));

$user->data = $data; //set the 'data' property

$user->save(); //save the new user to the database

 

The advantage is that later on, when they log in, you can have code like:

 

$isLoggedIn = $user->login($_POST['email'], $_POST['password']);

if(!$isLoggedIn) { /*do something*/ }

else { /*do something*/}

 

After calling the 'login()' method on valid credentials, the $user object will have its 'data' property set by retrieving the relevant DB record, and so then you can access other info about the user, update that info, check permissions, create orders - all by accessing properties and methods that you create on the User class.

 

If you'd like to learn from a book, the best I've found is PHP: Objects, Patterns, and Practice by Matt Zandstra. It's one of the yellow Apress books, and it's now in it's Third Edition. OOP didn't really "click" for me either until I read that book.

Link to comment
Share on other sites

oop is for like..

 

if you wanted to have more than 1 instance of the same code..

 

I'll write up a little class for you :)

 

<?php
class Game {
	public $players, $turn;
	public function changeTurn() {
		$this->turn = (($this->turn >= count($this->players)) 0:$this->turn + 1);
		echo "It is now {$players[$this->turn]->name}'s turn!";
	}
	public function isTurn($player) {
		return (($player === $players[$this->turn])? true:false);
	}
	public function addPlayer($name) {
		$this->players[] = new Player($name);
		echo "New Player Has Joined!";
	}
	public function scoredAPoint($score) {
		$this->players[$this->turn]->score += $score;
		echo "{$this->players[$this->turn]->name} Scored {$score} Points!";
	}
}
class Player {
	public $name, $score;
	public function __construct($name) {
		$this->name = $name;
		$this->score = 0;
	}
}
?>

 

thats an example of a little game.. you can like make it an actual game with a server connection and stuff.. basically Player is an instantiable object.. to keep data specific to that Player

 

the Game object is the object which indexs all of the players, its more of a package than an object..

 

but if you did make it an actual game, you would add connectivity functions to the Player class.. not the Game class, because each player needs to test connectivity individually.. etc..

 

a class for the MOST PART is just to have a batch of values and functions that work independantly and can be reused..

 

 

heres a script I made a while ago, its a server->client script.. it is long long ago so I don't know how good it is anymore, but it is a great example of using OOP :)

 

http://lovinglori.com/newServer.phps

 

I also wrote a connection class.. which you can use to create multiple connections.. wrapped in along with lots of easy to use functions..

 

 

<?php
// Author: Russell Crevatas
// E-Mail: RussellonMSN [AT] HotMail.com ~ Available For Hire
// Scripted For: AltScripts.net
class Connection {
    private $user, $pass, $host, $connection, $database, $lastResult;
    public function __construct($host,$user,$pass,$db = null) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->connect();
        if ($db != null) {
            $this->db($db);
        }
    }
public function close() {
	mysql_close($this->connection);
}
    private function connect() {
        $this->connection = mysql_connect($this->host,$this->user,$this->pass);
    }
    public function db($database) {
        $this->database = $database;
        mysql_select_db($this->database,$this->connection);
    }
    public function query($query) {
        $this->lastResult = mysql_query($query,$this->connection);
        return $this->lastResult;
    }
    public function fetch_assoc($result = null) {
        $res = ((!$result)? $this->lastResult:$result);
        if ($res) return mysql_fetch_assoc($res);
        return false;
    }
    public function fetch_array($result = null) {
        $res = ((!$result)? $this->lastResult:$result);
        if ($res) return mysql_fetch_array($res);
        return false;
    }
public function fetch_object($result = null) {
        $res = ((!$result)? $this->lastResult:$result);
        if ($res) return mysql_fetch_object($res);
        return false;
    }
    public function escape($string) {
        return mysql_real_escape_string($string,$this->connection);
    }
    public function rows($result = null) {
        $res = ((!$result)? $this->lastResult:$result);
        if ($res) return mysql_num_rows($res);
        return false;
    }
    public function id() {
        return mysql_insert_id($this->connection);
    }
public function error() {
	return mysql_error($this->connection);
}
}
?>

 

this is the version from an older project I've worked on, I've updated this class since.. however, the beauty of this being an object.. is I don't need to remember to specify an mysqlresult (which you get from mysql_query) in mysql_fetch_assoc and stuff.. since its an object you'll really only run 1 query at a time.. but in the event you do want to hold 1 result set and process another before the prior.. you can specify an optional field $result :)

 

these are all 3 good examples of proper oop..

 

making a class just for 1 page which really doesn't NEED oop.. is just gonna give you a function feel to classes, classes are more powerful than just for that :), although they lack in alot of ways in PHP compared to other languages, they're st ill really handy :)

Link to comment
Share on other sites

If you'd like to learn from a book, the best I've found is PHP: Objects, Patterns, and Practice by Matt Zandstra. It's one of the yellow Apress books, and it's now in it's Third Edition. OOP didn't really "click" for me either until I read that book.

 

This, right here.  Zandstra's book is a great introduction to the subject.

 

Regarding your registration class, you have some questions to answer:

 

1. Do you need an instance of this class, or can it be static (no constructor, with all functionality handled by static methods)?

 

2. What will the registration class return when someone is registered, if anything?  IMO, it makes sense to return a User object whose 'loggedIn' field is set to true so you can pass it around via sessions, thereby turning your registration class into a factory.  Just a thought.

 

3. What else needs to happen during the registration process?  Extra logging?  Error handling?  You may be well served by utilizing the Observer pattern here.

Link to comment
Share on other sites

$user = new User();
$data = array('first_name'=>$_POST['first_name'], 'last_name'=>$_POST['last_name'], 'email'=>$_POST['email'], 'password'=>md5($_POST['password']));
$user->data = $data; //set the 'data' property
$user->save(); //save the new user to the database

 

As User being part of the domain, and models being free of storing and presenting themselves, the correct approach would be:

 

$user = new User($data);
$userRepo->save($user);

 

$isLoggedIn = $user->login($_POST['email'], $_POST['password']);
if(!$isLoggedIn) { /*do something*/ }
else { /*do something*/}

 

The same applies here, a User is not responsible for authentication:

 

$authService = new AuthService();
if($authService->logon($user)) {

Link to comment
Share on other sites

*Sorry, been out-of-state for the past week and just trying to get caught up on my OP.*

 

 

This, right here.  Zandstra's book is a great introduction to the subject.

 

I have heard this and would like to read this book, but for right now want to focus on my specific issue.

 

 

Regarding your registration class, you have some questions to answer:

 

1. Do you need an instance of this class, or can it be static (no constructor, with all functionality handled by static methods)?

 

Good question.

 

 

2. What will the registration class return when someone is registered, if anything?  IMO, it makes sense to return a User object whose 'loggedIn' field is set to true so you can pass it around via sessions, thereby turning your registration class into a factory.  Just a thought.

 

Well, the process would go like this...

 

- User completes registration form

- System verifies required fields are completed

- System verifies emails match

- System verifies passwords match

- System verifies email is valid

- System verifies password is valid

- System verifies email is unique

- System creates User record

- System notifies User account was created

- System requires User to log in

 

I was thinking "Authentication" could be a separate class...

 

 

3. What else needs to happen during the registration process?  Extra logging?  Error handling?  You may be well served by utilizing the Observer pattern here.

 

I don't follow you?

 

Another reason I wanted to make "Registration" a class is that it then be extended.  For an e-commerce site, I've been advised by others to "make it quick and simple before people leave", but for something like "Forum Registration", I would like to add extra things like...

 

- System creates User record

- System notifies User account was created

- System requires User to activate account

- System sends "Activation email" to User

- User clicks on "activation link"

- System receives incoming "activation email"

- System activates account

- System instructs User to log in

 

 

TomTees

 

 

Link to comment
Share on other sites

$user = new User();
$data = array('first_name'=>$_POST['first_name'], 'last_name'=>$_POST['last_name'], 'email'=>$_POST['email'], 'password'=>md5($_POST['password']));
$user->data = $data; //set the 'data' property
$user->save(); //save the new user to the database

 

Can you store the data in separate variables or must it be an array?

 

 

As User being part of the domain, and models being free of storing and presenting themselves, the correct approach would be:

 

$user = new User($data);
$userRepo->save($user);

 

What are "models"?

 

What is a "$userRepo"?

 

 

$isLoggedIn = $user->login($_POST['email'], $_POST['password']);
if(!$isLoggedIn) { /*do something*/ }
else { /*do something*/}

 

The same applies here, a User is not responsible for authentication:

 

$authService = new AuthService();
if($authService->logon($user)) {

 

If I understand you, I too wanted to make "Registration" and "Authentication" as behaviors/services/processes that were separate classes, but that interact with the User class.

 

 

 

TomTees

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.