Posts Tagged ‘OOP’

Out of boredom I decided to create a very simple wrapper class for mysql database management. This class, as I mentioned, is extremely simple. However, for those wishing to learn more about Object Oriented programming, and how to implement a class that is useful, this is a good place to start. Anyone wishing to learn more about OOP could take this basic class, and make it into something that is much more useful.

Note: This class is untested. I haven’t actually ran the code, but I reviwed it to make sure any simple syntax/conceptual errors were removed.

If there is a syntax error or anything you see, leave a comment below so I can fix it!

Functionality

The class has very limited functionality. It basically provides normal mysql functionality (like querying, fetching rows, and fetching all the rows of a result set) and has a built in sanitizing function.

Improvements

This class is by no means complete or even useful. However, there are many improvements that someone could add to this that would not only make this class fairly useful, but is also great practice. Some obvious improvements could be as follows:

  • function to build and execute a query based on function parameters (like table, what to select, and where/order by statements(s)
  • an insert function that builds and executes a query based on parameters (table to insert, array of columns, and an array of corresponding values
  • stronger validation/sanitization

There are many many more things you could add to this class. A little competition for the readers: Submit your version of the class below with added features. The best/coolest class will get a free page with links/advertisement to their website (or a website of their choice)


<?php
class DB_manager {
 private $database;//database you wish to connect to
 private $username;//mysql username
 private $password;//myysql password
 private $server;//mysql server to connect to
 private $link;//variable to hold mysql connection link
 private $currentResult = false;

 private $query;

 //simple error reporting function.
 private function reportError($error){
 echo $error;
 }

 //constructor
 public function __construct($username, $password, $server="localhost"){
 $this->server = $server;
 $this->username = $username;
 $this->password = $password;
 }

 //connect
 public function connect($database){
 $this->link=mysql_connect($this->server,$this->user,$this->pass);
 //make sure we connected correctly
 if (!$this->link) {//open failed
 $this->reportError("Could not connect to server: <b>$this->server</b>.");
 }
 $this->database = $database
 if(!@mysql_select_db($this->database, $this->link)) {//no database
 $this->reportError("Could not open database: <b>$this->database</b>.");
 }
 }

 //run query q
 public function query($q){
 $this->query = $this->string_escape($q);
 $this->currentResult = mysql_query($q);
 if (!$this->currentResult){
 $this->reportError("There was an error with your query: " . mysql_error();
 $this->currentResult = false;
 return false;
 }
 return $this->currentResult;
 }
 //returns row from the result a query returned
 public function fetch_row($assoc = true){
 if (!$this->currentResult){
 $this->reportError("There is no valid result set to return data from.");
 return false;
 }

 if ($assoc)
 return mysql_fetch_assoc($this->currentResult);
 else
 return mysql_fetch_array($this->currentResult);

 }

 public function string_escape($s){
 return mysql_real_escape_string($s);
 }

 public function fetch_all($assoc = true){
 if (!$this->currentResult)
 $this->reportError("There is no valid result set to return data from.");
 return false;
 }

 $array = [];
 if ($assoc)
 while ($row = mysql_fetch_assoc($this->currentResult)){
 $array[] = $row;
 }
 }
 else {
 while ($row = mysql_fetch_array($this->currentResult)){
 $array[] = $row;
 }
 }

 return $array;
 }
}

//usage
$db = new DB_Manager('username', 'password', 'server (usually localhost');
$db->connect("databse_name");

$db->query("SELECT * FROM sometable");

$rows = $db->fetch_all();

foreach($rows as $r){
 print_r($r);
}

&nbsp;

&nbsp;

?>

If you have any questions, leave a comment!

As a tutor and coding help forum poster, I notice many instances of people using OOP, but using it incorrectly. Now, i don’t necessarily mean that they have errors in their code, or that it isn’t logically correct, but rather that the programmer in question has problems with their concepts of OOP. In this post I’ll be discussing the very basic and common problems I see, and ways to think about OOP such that these mistakes can be avoided. I’ll only be going over two of the simplest OOP concepts, encapsulation and inheritance.

Object Oriented Programming: The Why?

Many people simply use Object Oriented Programming because its the “latest and greatest” paradigm in the computer science field. The problem is that they learn the syntax and semantics of OOP, but never truely learn what OOP is. Let me start by giving a basic explanation of what OOP brings to the table as far as programming is concerned.

First, the basic concept of OOP is instead of programming procedurally, or functionally, you program in such a way that your entire program consists of discrete, separate objects that interact with each other in certain ways. This concept is fairly easy to understand, but doesn’t quite explain how to implement such a program that takes advantage of all OOP has to offer. However, lets take a simple example to further illustrate this concept. Lets say we are writing a program to model driving a car. Each car is a separate object of course, but these objects are instances of the same class (in the case, a car), but have different properties. Some are fast, some are strong, and some have great gas mileage. Each car, consequently, is composed of many other discrete objects. Like the rear view mirror, or the engine (which in turn could be composed of other objects) and the tires (and of course these each have their own attributes). Then there is the driver of the car which is another object that interacts directly with the car. The Driver tells the car to drive, and the car in turn tells the engine to turn on, and tells the wheels to spin. The Driver doesn’t ever interact with the individual components of a car, but rather the car itself. The car interacts with each individual components. In (very PHP-like) pseudo code, this interaction might look something like

$Honda_Accord =  new Car();
$Honda_Accord->addEngine(new Engine());
//add rest of components
$bob = new Driver();
$bob->Drive($Honda_Accord);

//inside the drive method,
$Honda_Accord->start_engine();
$Honda_Accord->spin_wheels();
//etc..

Encapsulation

This is probably the most widely known but often misunderstood concepts that OOP brings to the table. The basic concept is that of data hiding. Each discrete object in your program has data inside of it, that it hides from the rest of the program. If we consider the example above, each car would have certain properties (like speed, gas mileage, etc.). These properties would only be changed or acted with by the car. The rest of the program cannot (and should not) have access to any of these properties. For example, the driver tells the car to start, but the car is the one that sends the signals to the tires to move. The driver doesn’t (and can’t) interact with each individual wheel.

Encapsulation is often widely misused though. I see misuse in many forms, but the most common are as follows. The programmer may completely forgo encapsulation (For example, he makes all data members public). The programmer also may take it too far (he makes every single data member private, even those that conceptual shouldn’t be). I also see many people doing a very curious thing. They make all (or most) of the classes data members private, but create mutators and accessors for all of them, essentially making them public, but writing a lot more code to do so. For example

class A {
private $some_int;
private $some_string;

public function get_some_int(){ return $this->some_int; }

public function set_some_int($i){ $this->some_int = $i; }

public function get_some_string(){ return $this->some_string; }

public function set_some_string($s){ $this-> some_string = $s; }

}

Now, trying to explain how to correctly use encapsulation is almost impossible, since it can be applied in so many ways. However, I often try to tell my students the following, which has mixed, but predominantly positives results: When deciding what data members to make public, which to make private, and which to make accessors or mutators for, consider the following. If we consider a data member, say int x, how is it going to be used? Is it only ever going to be accessed and modified inside the class. If so make it private. If it will be accessed outside of the class, but you only want to be able to change it inside, then make it a private variable with an accessor (like GetX()). If you are going to be accessing and changing it outside of the class without any restrictions (IE a programmer using this class can set the value of x to any reasonable value) Then make it public. If you want to make it so that the data member can be set and retrieved outside the class, but setting the variable has restrictions (Like x cannot be over 10 or below 0) then make the variable private, and use an accessor and mutator.

Lets take an example. Lets say we are creating a Person class. The name of the person would obviously be private (since no one can change someone’s name but the person) but with an accessor (people can still ask for their name). The amount of cash someone has would again be private, but would have an accessor (someone can ask how much money they have) and a restricted mutator (someone can’t just set the amount of money they have, but a store keeper can ask for a certain amount, or give a certain amount back as change.) The class could look something like:

class Person {
private $name;
private $cash;

public function getName(){ return $this->name; }

public function getCash(){ return $this->cash; }

public function giveChange($c){ $this->cash += $c; }//function to return change back to user

public function pay($price) { $this->cash -= $price; }//function to pay for something

}
<h3>Inheritance</h3>
Inheritance is one of the most commonly misused concepts I see. Sometimes even more than encapsulation (since its a bit easier to understand the implications of it in a conceptual sense, so its much easier to correct past mistakes). However, inheritance is slightly more complex than encapsulation. The basic concept is rather easy to understand. Inheritance in OOP models inheritance in real life fairly closely. You have a Base or Parent object, and you have a Derived or Child object that inherits from it. The child has all the properties that a parent has, and more.

The main problem I see many students and novice programmers trip up on is having children inherit from parents for no apparent reason. For example (and this is a real example) one of my students had a lab recitation to model a car (much like the example above, but much simpler). Cars were composed of Engines, and Wheels and had some basic attributes (like model name and number). This student decided to have the engines and wheels inherit from the car because they were part of the class, and he took this to mean that they had to inherit from cars. This shows two things. One, laziness, and two, a complete misunderstanding of the concept of inheritance.

When deciding on using inheritance, take the following into consideration:

Say we have a system where we have a few different classes. Lets say that these classes all have some sort of similarities. If they do, then I would take these similarities (generally in the form of the same attributes, or the same methods) , move them into a base class, and have my other classes derive from them. Inheritance can be used to avoid having to repeat code. However, inheritance is unnecessary or irrelevant if we have two classes that are quite different from each other, even if they seem to have some similarities. For example, if we are creating a GUI system, we may have a bunch of different shapes. Each shape would have some similar methods and attributes (Like the name of the shape, and a method for drawing the shape). Each shape should derive from some Base shape class. Another example would be a system where we have musicians and a music store. Each musician and each store would have a store of instruments (for example, a musician may have a guitar and drums, and a store may have a whole selection of guitars, basses, drums, etc.) Musicians and stores would also each have names, and other things. However, it really wouldn't make sense for either musicians to inherit from stores, or stores from musicians since each has unique data members that the other doesn't have.

Taking the shapes example, the code may look something like



class Shape { //base shape class
protected $name= "abstract shape";//protected so derived class can access of course

public function draw(){ ... }

}

class Triangle extends Shape {//triangle class that inherits from shape class

private $height;
private $base;

function _construct(){ $this->name = "triangle"; } //constructor to set name of this class to triangle

}

 

If you have any questions, comments or feedback, please let me know in the comments!

public function draw() { ... draw the triangle ... }

As a student of Computer Science, and a web developer, one of my passions is PHP, and over the years this language has developed with some quite robust functionality. The topic I will be discussing today is Object Oriented programming. I will give an introductory overview to the concept in general, and provide some code examples. At the end I will discuss why this paradigm is useful.

You should have a working knowledge of:

  • PHP in general
  • Basic programming concepts (flow control, different variable data types, looping, etc.)
First, what is object oriented programming (hereby abbreviated as OOP)? Well in its most basic form, OOP is a programming style in which the programmer separates the differing functionality of his program into distinct objects. For a simple example, consider a program that would simulate a car running. Each different part of the car could be its own object (IE the wheels are one object, the chassis another, and the engine another still). All these objects work together, but separately. The engine tells the wheels to turn, and the wheels tell the chassis to move. This is an oversimplified example, but the point remains the same. All the objects in this program work together to provide the functionality of the program itself.
Now that we have a basic idea of what OOP is, lets start discussing some concepts and vocabulary. First, the basic vocabulary (with code examples) that we will need in order to continue.
Class: This is what PHP calls the prototype for objects. This holds all the information about any objects created from these, including its attributes, methods, etc.
Instantiate: This is the process in which we create an object of some class.
Method: A method is a function that is part of a class, and is only available to the class (IE you can not call a method without an instance of a class)
Attribute/Property: Any variables that make up the class
Private: This defines the scope of a method or property. Private means that you may only access the method or property inside the class
Public: This defines the scope of a method or property. Public means that you can access the method or property anywhere it is available.
Now lets look at a code example that will demonstrate each of these words
class MyClass {
public $property1;//this is a property. set to public scope
private $property2;//this is a property set to private scope

public function Method1(){//this is a method, set to public scope
$this->property2 = "Cool";
echo "Hello World!";
}
private function Method2(){//this is a method set to private scope
echo "You can't see me! Or can you?";
}
public function CallMethod2(){//This is a method set to public scope
$this->Method2();//we can call Method2 here because we are inside the class
}
//note we use the variable $this with the -> operator to access class variables and methods
}//end class

//now lets use our class
$MyClassVariable = new MyClass;//this is instantiating. we just created an instance or object of type MyClass
//we use the -> operator to access methods/properties
$MyClassVariable->property1 = "Hello";//We can access property1 because its public
$MyClassVariable->property2 = "Error! Error!";//We can't access property2 because its private

$MyClassVariable->Method1();//this would output: Hello World!
$MyClassVariable->Method2();//this would produce an error. Remember, Method2 is private!
$myClassVariable->CallMethod2();//This would work and would say: You can't see me! Or Can you?
//we need an instance of the class to call its methods
//we cant do something like
MyClass->property1 = "Something";

Now lets examine what went on here. First we created a class called MyClass, in which I created a few properties and methods. I then instantiated an object of that class, and showed various ways to use the methods and properties (and ways in which you can’t use it depending on the private/public scope of the method or property).

Now you may be thinking, what is the point of private methods/properties? Public kind of makes sense because we can keep certain information together in one class, and still access it, but private means we can’t touch it even if we want to. Well that gets to my next point, which is a concept called encapsulation. This is probably the most basic concept in OOP, the usually the first you learn.

Encapsulation is easy to understand, but may be difficult to understand the usefulness, but I will try my best to explain it as simply as I can. Encapsulation is the practice in which you make certain properties or methods of an object private to protect it from the outside world. Simple enough right? But why would we want to do this? Well consider the following:

Say we have a class called Person, with all the attributes and methods we would expect it to have (Like the property name, the method sleep, etc.) Now, for his name property, we could make it public, but that implies that other people, and other entities in the world would and should be able to change the person’s name. In reality, a person receives his name when he is born (or in programming terms, instantiated) and it doesn’t ever really change (well, ignoring paying to change your name, but lets ignore that for this simple example.) Make sense? There are many different examples we can cite of information that should be part of an object, but really shouldn’t be able to be changed by other people. But, the next questions that may arise would be: How do we ask the person’s name? And how do we give the person a name when they are born? Well that brings me to my next point. There are two special methods we can utilize (well really, one is a special method and the other a type of method.) Called the Constructor and an Accessor.

Constructor: This is a special method which, when defined, is called when you instantiate an object. If you add parameters to this function, you must specify them in the creation of the line (more below)

Accessor: This is a type of method that allows the programmer to access the value of of a private property without being able to change it.

Lets take a code example using our person from above

class Person {
private $name;

function __construct($n){//here is our constructor. this is called when we instantiate a person object, or when a person is "born"
$this->name = n;//set our private data member to passed in name
}

public function getName() {
//this is an accessor. It returns the name of the person
//but doesn't let anyone change it
$return $this->name;
}
}//end class

$bob = new Person("Bob");//we pass in Bob to the constructor. now $bob has a name!
echo "Hello, my name is " . $bob->getName();//echos: Hello, my name is Bob

And there we go, a very basic class that uses the concept of encapsulation to keep its private data safe from the outside. As a general rule, making your properties private, and creating ways to access them is the best way to adhere to encapsulation. Of course, with accessors, there are always methods to change a private variable, called a mutator. I will not be going over that in much detail.

Now, enough of the hypothetical’s, how about we do something useful? Ok, lets create a simple database class that makes use of all the concepts we have discussed so far.

class simpleDB{
private $host;
private $password;
private $username;
private $link = null;//example of setting a default value

function __construct($h="localHost", $p="", $u="username"){//default mysql values
$this->host = $h;
$this->password = $p;
$this->username = $u;
}

public function Connect() {
$this->link = mysql_connect($this->host, $this->username, $this->password);
return $this->link;//return the connection for testing purposes
}

public function Select_DB($database){
if ($this->link){//if its not null
return mysql_select_db($database);
}
return false;
}

public function Query($query){
if ($this->link){
return mysql_query($query);
}
return false;
}
}//end class
The class above could be known as an wrapper class, because it is a class wrapped around existing functionality to put it into a neat little package. If anyone would like an explanation of this class I can try to explain in the comments, but try to figure out how it works, and what parts exemplify which concepts on your own! Hope you guys enjoyed this tutorial