Jump to content

Recommended Posts

So I am sitting and trying to figure out, how making classes in php, and using OOP in php would be useful. I do a lot of PHP + MySQL.

 

Let me give an example of the kind of things I do, which are common, and perhaps somebody could provide some OOP examples:

 

Lets assume we have the following MySQL table schema.

 

Customers

id
first_name
last_name
company_name

 

Orders

id
associated_customer_id
number_of_products
price_per_product

 

If I want to pull all customers I would simply do something like:

 

$sql = "SELECT * FROM customers";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($result))
{
   echo 'First Name: ' . $row->first_name;
   echo 'Last Name: ' . $row->last_name;
   //And So Forth
}

 

Now it would be cool if I could simply create a new 'customers' class object and then call a class member or simply GET and SET class member variables. I am just not sure how to go about doing it.

 

Thanks for the help.

 

Ok, so here is what I came up with.

 

class Customer
{
	var $id;
	var $first_name;
	var $last_name;
	var $company_name;

	//Constructor - Creates a customer with all properites set to null.
	function Customer()
	{
		$this->id = NULL;
		$this->first_name = NULL;
		$this->last_name = NULL;
		$this->company_name = NULL; 
	}

	//Overloaded Constructor - Creates a customer with all properties set from the customer id.
	function Customer($id)
	{
		$sql = "SELECT * FROM customers WHERE customer_id = " . $id	. " LIMIT 1";
		$result = mysql_query($sql) or die(mysql_error());
		while($row = mysql_fetch_assoc($result))
		{
			$this->id = $id;
			$this->first_name = $row['first_name'];
			$this->last_name = $row['last_name'];
			$this->company_name = $row['company_name'];
		}
	}
}

//Create and instanciate of the customer object
$myCustomer = new Customer();

//Create and instanciate of the customer object
$myCustomer2 = new Customer(121);

 

I am not understanding the benfit of this? It took like 5 times as long, and a lot more typing. Pehaps somebody could explain further.

I am not understanding the benfit of this? It took like 5 times as long, and a lot more typing.

 

Yeah, but now, anywhere you need a customers details all you need call is....

 

<?php

  include "customer.class.php";
  $myCustomer2 = new Customer(121);

?>

Ok, so I guess that is nice, but whats the trick to creating a new customer, or updating a customer? Is there such things at GET and SETS like in C#? Also, if I made a class for Order, does Order extend Customer, or inherit the Customer class?

 

I guess I don't quite fully understand how I can make a customer class which allows, retrieving, creating, updating, and deleting of data via a MySQL database.

 

Also in my current class a Customer is only one, how would I pull all customers? Like I want a list of all customers?

here is how i designed my personal db class

 

i have a parent db class that handles all of the db interaction, then i have classes for each table in the db with static methods that contain prepaired statements to run queries

 

class db{

//connects to the db, handles queries etc, also a singleton

}

 

class user extends db{

public static function insert($name, $pass){

//insert query

$this->runquery($query); //runquery() is in db

}

}

 

and i use it like

 

require 'user.sql.php';

$add_user = user::insert($name, $pass);

 

thats just one of a billion ways to handle it, and it works well for me

here is how i designed my personal db class

 

i have a parent db class that handles all of the db interaction, then i have classes for each table in the db with static methods that contain prepaired statements to run queries

 

class db{

//connects to the db, handles queries etc, also a singleton

}

 

class user extends db{

public static function insert($name, $pass){

//insert query

$this->runquery($query); //runquery() is in db

}

}

 

and i use it like

 

require 'user.sql.php';

$add_user = user::insert($name, $pass);

 

thats just one of a billion ways to handle it, and it works well for me

 

Could you provide more of the code? Not sure I follow that. One thing I want to do, is give me flexability to add and remove columns from a table without making a lot of changes all over the place.

you could do worse than reading up a bit more on Active Record: http://en.wikipedia.org/wiki/Active_record . I actually use an implementation based on CakePHP (which in turn is based on Rails), so I can just do stuff like:

 

<?php
// simple example to read user with 'id' of 3, change its username and change it back.
// pointless exercise but just an example of what can be done....
$user = new User(); // user class extends model class

$user->id = 3;
$user->read(); // SELECT query: SELECT * FROM users WHERE id = 3

$oldusername = $user->username;

$user->username = 'hello';
$id = $user->save(); // UPDATE or INSERT query depending if 'id' field is set in my object

// UPDATE users SET username = '$oldusername' WHERE id = 3
$user->saveField('username', $oldusername); 
?>

 

the point really, as thorpe suggested, is that I dont need to keep rewriting common queries, or even escaping data for queries. my methods automatically run inputted data through mysql_real_escape_string and built the queries for me. Consider if I create a registration page. My User model can be used again and again on many sites, even if my table structure alters, with minimal changes rather than rewriting entire queries. I also dont need to check whether to use INSERT or UPDATE when saving data. I can also change the DB to something like MSSQL, Oracle, etc without breaking my main code. Hell, I can even use flat file DB if I want, yet my code remains the same.

 

PHP does have __get , __set and __call magic methods should you need them, which you can see at work in my example where i use $user->username and $user->id . See here

 

Hope that helps!

Cheers

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.