Jump to content

Procedural to OOP


needs_upgrade

Recommended Posts

John Kleijn said that to avoid writing "crappy code", we should learn OOP and common OO principles. I've started reading OOP tutorials including the design patterns. And John is right, this is not an easy task. It's a shame because I'm finding it hard to absorb the tutorials.

 

Is it ok if I'll show you some of my procedural codes and you'll show me how to code some of its parts in OOP? I learn faster by playing with relevant codes. I hope it's ok with you guys.

 

 

Basically, all my php files look like this:

ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

include("fxns.php");
define('TITLE', 'Page Title');
session_start();

if(isset($_SESSION['user_id'])) {
if (validate_user() == true) {
	print_header(TITLE); // echos html codes
	print_navs();           // echos html codes
	//contents here
                // calling more functions here
                print_footer();
}
} else {
header('Location: login.php');	
}

 

and my fxns.php would look like this:

include("connect.php");

function validate_user() {
$sql = "SELECT uo.ip_address, uo.session_id, uo.user_agent, uo.activity
		FROM users_online uo, users u
		WHERE uo.user_id='$_SESSION[user_id]' AND uo.user_id=u.user_id";
$res = mysql_query($sql); $row = mysql_fetch_array($res);
$ip_address = $row[0]; 
$session_id = $row[1]; 
$user_agent = $row[2]; 
$activity = $row[3]; 

$res2 = mysql_query("SELECT config_value FROM config WHERE config_name='inactivity'");
$row2 = mysql_fetch_array($res2); $inactivity = $row2[0];

$res3 = mysql_query("SELECT locked, invalid_ip FROM users WHERE user_id='{$_SESSION[user_id]}'");
$row3 = mysql_fetch_array($res3); $locked = $row3[0]; $invalid_ip = $row3[1];

// verify user's IP address
if($ip_address != $_SERVER['REMOTE_ADDR']) {
	show_invalid_ip($_SERVER['REMOTE_ADDR']); // echo some HTML
}
// verify if the the session id and user's session id are the same
elseif ($session_id != session_id()) {
	show_invalid_sid(); // echo some HTML
}
// verify if the browser software is the same
elseif($user_agent != $_SERVER['HTTP_USER_AGENT']) {
	show_invalid_user_agent(); // echo some HTML
}
// verify if the user is locked
elseif ($locked == 1) {
	show_locked($invalid_ip); // echo some HTML
}
// verify if the user has been inactive for $inactivity mins
elseif( time() > ( $activity + ($inactivity * 60) ) ) {
	show_s_expired($inactivity); // echo some HTML
} else { 
	update_user();
	return true;
}
}

function update_user() {
$maxtime = time() - 1800;
mysql_query("UPDATE users_online SET refurl='{$_SERVER['HTTP_REFERER']}' WHERE user_id='$_SESSION[user_id]'");
mysql_query("UPDATE users_online SET activity='".time()."' WHERE user_id='$_SESSION[user_id]'");
mysql_query("DELETE FROM users_online WHERE activity < '$maxtime'");
}

 

 

Would you be kind to write some of its part in OOP? Thanks so much..

Link to comment
Share on other sites

You dont necessarily HAVE TO write in OOP. OOP is meant to make certain methods easier to work with. For example, you can create an OOP class for connecting to and querying a database. PHP does have methods for this, however you may want to do some custom commands, or make a query generator, where all you would do is something like $db->query($table,$where_clause,$order); where $db is your object and query is a function within it. If you write the code correctly, you dont ever have to write SQL statements. You would use this as a "wrapper" for the real thing.

 

Of course, that was a really rough example, but hopefully you understand the point of OOP a little better.

Link to comment
Share on other sites

Also, I think it's difficult to attempt to translate code from procedural to OOP as your first attempt.  There's often an implicit assumption that beginners have where they think there's a 1:1 correlation between the two styles of coding.  There's not.

 

Your best bet is to start at the beginning.  Learn the basics - syntax, how to combine objects, how to extend them, etc.

Link to comment
Share on other sites

aba hit it on the head.

 

When you write functions, you're writing OO programming (at least, you have the methodology of OO). You're removing a chunk of your procedural PHP and placing it in a function that can be called from anywhere whenever it's needed without being rewritten in its entirety.

 

True OO programming (that is, using objects) involves "collecting" similar functions and variables and placing them into a class where they're all together.

 

I tend to use quite a few classes to handle tasks including sessions, validating user input, processing HTML (including writing HTML to the browser), interacting with the database (including creating logs of errors and webpage use) as abazoskib suggests.

 

As you write functions for a PHP program, see if some of the functions seem to have a common purpose (IE. you have 2-3 functions that are meant to validate user inputted data) - it's probably a good time to make a class for it! This is how I got started writing classes, and once I got started I found it easy to find new methods that I could add to my classes. I even sometimes have parameters or methods in my functions that are there "just in case" I need them at some point while programming (for example, my database class records the last query run on the database and has since I've written - only a month or two in development have I ever used it for debugging, was glad I had it even though I haven't used it before or since).

Link to comment
Share on other sites

True OO programming (that is, using objects) involves "collecting" similar functions and variables and placing them into a class where they're all together.

 

Not really. What you're describing are name spaces. OOP is about modelling things using objects. Each object has a state represented by its properties, and the state of the world can be changed by calling an object's methods. As such objects interact with each other using each other's public interfaces, much like real world objects interact with each other in some sort of way.

Link to comment
Share on other sites

Merely stuffing code into collections of functions != OOP.

 

Agreed, unless you're:

 

removing a chunk of your procedural PHP and placing it in a function that can be called from anywhere whenever it's needed without being rewritten in its entirety.

 

In which case it's not really OO since you're not using objects, but it employs the same methodology.

Link to comment
Share on other sites

Merely stuffing code into collections of functions != OOP.

 

Agreed, unless you're:

 

removing a chunk of your procedural PHP and placing it in a function that can be called from anywhere whenever it's needed without being rewritten in its entirety.

 

In which case it's not really OO since you're not using objects, but it employs the same methodology.

 

That's called creating library code.  Again, there's more to OOP than migrating code to a group of similarly themed functions and including them in the global scope.

Link to comment
Share on other sites

I'll concede the point, but only because this has become a semantic argument over the definition of OOP, and to argue that there is a true definition is silly and pointless.

 

However, I will point out that if you get hung up on making "proper" OOP programming, you're going to waste time producing code that's sub-par.

 

Whether OOP is better at all is debatable, it's more a question of what methodology do you approach your programming with to solve a particular problem (balancing things such as security, efficiency, and ease of understanding the code).

Link to comment
Share on other sites

I'll concede the point, but only because this has become a semantic argument over the definition of OOP, and to argue that there is a true definition is silly and pointless.

 

However, I will point out that if you get hung up on making "proper" OOP programming, you're going to waste time producing code that's sub-par.

 

Whether OOP is better at all is debatable, it's more a question of what methodology do you approach your programming with to solve a particular problem (balancing things such as security, efficiency, and ease of understanding the code).

 

- I respectfully disagree with all the points you mentioned.. as far arguing over the true definition of what OOP actually is is relevant if explaining this to someone. Giving the incorrect def could certainly cause confusion to the uninitiated.

 

- Calling making proper OOP programming a waste of time producing code that's sub-par is absurd IMO. Perhaps beginners will not 'get it' right away, but properly written OOP brings the advantages of loose coupling, encapsulation, composition/aggregation and all that other good stuff that procedural code doesn't have. This isn't to suggest that only good code is OOP code... nor is this to suggest that everything must be OOP... but as you delve into OOP much more, the advantages of it (along with design patterns) becomes very apparent.. its a tool set (much like anything else), that when employed intelligently, taking proper design principals into account will more than save time and frustration.

Link to comment
Share on other sites

back to helping out OP...

 

Like people have said, there is no real straight procedural to OOP conversion. It is more a different way of producing code. Like daniel said

 

OOP is about modelling things using objects. Each object has a state represented by its properties, and the state of the world can be changed by calling an object's methods. As such objects interact with each other using each other's public interfaces, much like real world objects interact with each other in some sort of way.

 

To explain this further, you posted a function called validate user. Now if your program was real life, that method would be part of a security system right? Now what else might go into a security system. A way of validating the information the user gives (so they don't just hack our security system). maybe a large burly man to "ban" them if they get uppity?

 

That would be modeling a security system via objects. Now for a website, we may need to model many things. For example, there could be a user class, which stores all the users information (including session info) and that user class may interact with the security class to log in, or get to restricted areas. Now we have objects interacting with each other. There are many more aspects of OOP that I can't cover in this post, but that should give you an idea for how you can (note i said can, not should) implement OOP

 

Now lets take a simple example. The security system for example. assuming you already know the syntax of classes and objects in PHP, lets create a simple class (for sake of ease, i'm just going to declare methods, and not write how they would be implemented. I'll leave the fun parts for you)

 

class securityRobot9000 {

//lets declare some methods that our security robot may have
validateUser($username, $password){
}//log in a user?

validateInput($input){
}//protect against SQL injections

banUser($username){
}//ban a user

checkAdmin($username){
}//check if a user is an admin

//etc
}//end class

 

now How could we use this class? well assuming we already defined a user class, we could log them in like so

//assuming $user and $login are populated with values from a form
$r9k = new securityRobot9000;
//check if user is correct
if ($r9k->validateUser($username, $login)){
$user = new userClass($username);
//do some session stuff
}

 

now how you implement these classes is really up to you, and with all programming languages, you have choices. You could pass this object through a session variable, instantiate the class with a session variable, etc. etc. First and foremost, I would read some tutorials, learn the syntax and rules of good use, and try a very simple implementation (a security class is probably a good start for a website) then build from there

Link to comment
Share on other sites

I think OOP is just a way for smarty pants programmers to act cooler than each other by displaying their understanding of big words. (Okay, I don't REALLY believe that, but it is funny how most OOP conversations go down this same road)

 

These conversations go down this road simply because people who don't fully grasp OOP but think they do attempt to tell those who actually know what they're doing that they're wrong.

Link to comment
Share on other sites

OOP was a hard concept for me grasp too at first.

about 20 minutes in the video. Where he shows this tree model of "animals".

 

Then it hit me, Imagine this.

 

$bob = new $human('male');

$viconia = new $human('female');

 

THat would generate 2 object with an array tha tcontains all the information about hair color, body size, skin color and everything perhaps randomly generated.

 

These objects of class "human" would extend mammal, mammals would extend animals, and animals would extend matter, and matter would extend physical laws and gravity. Any number of class could branch off certain parts and have private variables. For example you would not beable to access a variable from a bird class that extend off animal from human becuase its protected. Also on the bottom class of material laws. (matter) human would inherit to be flammable while the class "rock" that extends from it wouldn't. The whole world really made up in way, yes sorry you are all objects, so welcome to the matrix!! LOL :D

In the perfect matrix there is no layer of "procedural" code that overlays this. Its all one object that hums together. Sorry if that sounds ridicolous. I have an extreme visual imagination.

 

I still haven't found any PHP code that does that yet. lol

But if it where this 1 line would start your whole application.

 

// After programming for 7 days, God said:

$start = new start;

echo "welcome to the matrix"; ;)

 

 

Link to comment
Share on other sites

And that doesn't sound conceited...

 

so it's conceit to be offended when someone comes along and marginalizes work that you've taken the time to specialize and excel at, to nothing more than a "holier-than-thou" attitude? i think you're confusing conceit with indignity here.

Link to comment
Share on other sites

Lets face it, OOP is not that easy to explain. And its certainly just as easy to throw around OOP related words without knowing what they mean. As far as the original problem goes, unless you have a specific need for OOP, don't assume you need to convert any procedural code. To learn OOP, its one of those things, for me personally that did not sit right for a while after learning it, but was brewing in my head. It just clicked one day, mainly because I needed an OOP solution, and I realized how the ideas(all the big words) came together.

Link to comment
Share on other sites

And that doesn't sound conceited...

 

so it's conceit to be offended when someone comes along and marginalizes work that you've taken the time to specialize and excel at, to nothing more than a "holier-than-thou" attitude? i think you're confusing conceit with indignity here.

 

No, not at all. Being indignant because somebody says 'OOP is a waste of time' is perfectly understandable, even expected behavior. But stating that somebody who doesn't favour OOP techniques is obviously wrong, without a single supporting statement gives the impression of conceit. As it happens I agree with (what appears to be) Nightslyr's general outlook, that the majority of arguements against OOP aren't really against OOP per se, more against missuse of OOP techniques. But that doesn't change the fact the statement sounded conceited.

 

 

Link to comment
Share on other sites

And that doesn't sound conceited...

 

I admit I thought about whether or not to hit 'Post' after writing that.  Ultimately, I feel it needed to be said.

 

I have no problem with people putting library code in classes.  I don't necessarily agree with the practice, but if it works for the coder in question, then they should go for it.

 

What I do take exception to is someone trying to tell a beginner that stuffing functions related by theme into classes is OOP.  It is not, and it gives the beginner the wrong idea of what OOP is and the point behind it.  Writing reusable code and understanding the separation of concerns - which is essentially all that ialsoagree described - is not OOP in and of itself.

 

Was my remark conceited?  Probably.  But I find it to be accurate as well.

 

Fake edit:

 

But stating that somebody who doesn't favour OOP techniques is obviously wrong, without a single supporting statement gives the impression of conceit.

 

I wasn't addressing ialsoagree's opinion on OOP.  I could care less if they loathe it or think it's the bee's knees.  I was merely making an observation based on their stated misunderstanding on what OOP actually is.

Link to comment
Share on other sites

To get back to the OP, you could have something like:

 

class UserManager
{
   private $sessionData;
   private $userList;

   public function __construct($sessionArray)
   {
      //do any security processing to ensure that the session data hasn't been compromised

      $this->sessionData = $sessionArray;
   }

   public function validateUser()
   {
      $userId = $this->sessionData['user_id'];

      //access the db, which may also be an object

      if(/* everything checks out */)
      {
         $legitUser = new User($ip_address, $session_id, $user_agent, $activity);
         $this->addUser($legitUser);
         return true;
      }
      else
      {
         return false;
      }
   }

   private function addUser(User $user)
   {
      $this->userList[$user->getSessId()] = $user;
   }

   public function getUser(User $user) //could also write this to accept the session id as an argument... it'd look cleaner that way
   {
      if($this->userList[$user->getSessId()])
      {
         return $this->userList[$user->getSessId()];
      }
      else
      {
         //error
      }
   }
}

class User
{
   private $ipAddress;
   private $sessId;
   private $userAgent;
   private $activity;

   public function __construct($ipAddress, $sessId, $userAgent, $activity)
   {
      $this->ipAddress = $ipAddress;
      $this->sessId = $sessId;
      $this->userAgent = $userAgent;
      $this->activity = $activity;
   }

   public function getSessId()
   {
      return $this->sessId;
   }

   //other similar functions
}

 

One of the key concepts behind OOP is that objects (like my hastily written UserManager) can contain other objects (Users).  That tends to be the core concept that many have difficulty grasping, so I figured I'd give you a taste of that early.

 

This was just a very rough idea of what you could do.  Your best bet is to start at the beginning and slowly work your way up to being able to build and manipulate objects yourself.

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.