MMOwned - World of Warcraft Exploits, Hacks, Bots and Guides  
Homepage Register FAQ Members Mark Forums Read Advertise Marketplace FPSowned


Go Back   MMOwned - World of Warcraft Exploits, Hacks, Bots and Guides > Programming > Server side > PHP
Reload this Page [Tutorial] PHP How to organize your classes | Part 1
PHP Discussions about PHP

Reply
 
LinkBack Thread Tools
[Tutorial] PHP How to organize your classes | Part 1
(#1)
Old
Tanax's Avatar
Tanax is Offline
Knight
Rep Power: 2
Reputation: 51
Tanax will become famous soon enough
 
Posts: 218
Join Date: Jan 2007
Location: Sweden
[Tutorial] PHP How to organize your classes | Part 1 - 04-23-2008


How to organize your classes
Part 1: Database class + config files


Section 1: Intro

Hello and welcome to this guide! This will be a guide with 2 or possibly 3 parts.
It will learn you who to organize your class files in a nice way, and how to write a good database class that gets your job done.

So, first we'll take a look at the structure and organizing of the files.

For this to be easier to explain(and for you to understand), I will just pretend that we have a projectfolder called "test", located in our root directory.

And since I do this on localhost, the folder I place my hosted files, is called "www". So what does this conclude?
We have:


Code:
www
- test


Everyone with me so far?


Right, so let's start the actual tutorial :P
We want to have an includes folder, where we will have everything that we want to include.


Code:
www
- test
- - includes


In the includes folder, we will have our config file for example(that's atleast what I will explain to you today) and a classes file which I also will go through today.
Some folders that you want to have inside includes, is for example gfx, js, templates, classes, plugins


Code:
www
- test
- - includes
- - - gfx
- - - js
- - - templates
- - - classes
- - - plugins


The folder we will concentrate on today, is the classes folder.




Section 2: The database class and the database interface

Right. Alot of people use database to store things. Not only is it faster than if you would store it with.. say a .txt file, but it's also alot safer, but the main
thing is that it's EASY to manipulate the data. This means that you could write neat admin panels to control your site layout, templates and lots and lots more!!

But in order to get a nice way of handling the database, you need a proper database class, that will provide a set of functions for you to use inside your classes.

This database class, will actually consist of 3 files.
iDB.php - This is our interface for the class.
DBmysql.php - This is the actual class for the database, in this case a mysql-database which I called mysql.php(convinient xD?) with the prefix of DB(DBmysql).
DB.php - This is our.. DB factory, which makes it easier to include the database file.

So let's start by taking a look at our interface!

An interface is merely a blueprint on how the class should look, what functions it have to contain. This is neccessary, because when you guys figure out
that you don't want to use a mysql database, but an oracle database, and you write your own db class(DBoracle.php), you will then see if your class follows the blueprint.

The interface is define with
PHP Code:
    interface iDB {
        
    } 
Pretty simple.
So what functions should the database have?
Well, first of all, we need a function that will set the values of the hostname, username, userpass and dbname. We would also need a function that connects.. etc etc.
I'm sure you can figure out by yourself all the functions that a database class should have.

This is my interface anyhow:
PHP Code:
/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/

    
interface iDB {
        
        public function 
setHandler($host$user$pass$data);
        public function 
connect();
        public function 
select();
        public function 
disconnect();
        public function 
query($query);
        public function 
fetch($sql);
        public function 
setTable($field$value);
        public function 
setCol($field$value);
        
    } 
2 very important functions are the setTable and setCol. I will explain later in the tutorial what they do, just keep them there!

So the next file, is ofcourse the database class itself.
As I mentioned before, this is just the mysql since it's most used.

PHP Code:
    class DBmysql implements iDB {
        
        private 
$host;
        private 
$user;
        private 
$pass;
        private 
$data;
        public 
$table = array();
        public 
$col = array();
        
        
        public function 
setHandler($host$user$pass$data) {
            
            
        }
        
        public function 
connect() {
            
            
        }
        
        public function 
select() {
            
            
        }
        
        public function 
disconnect() {
            
            
        }
        
        public function 
query($query) {
            
            
        }
        
        public function 
fetch($sql) {
            
            
        }
            
        public function 
secure($string) {
            
                        
        }
        
        public function 
setTable($field$value) {
            
            
        }
        
        public function 
setCol($field$value) {
            
            
        }
        
        
    } 
As you see, we IMPLEMENT the interface. So if you guys decide to create another dbtype class, you have to implement the interface.
And ofcourse, we have to have all the functions that we defined in the interface.

PHP Code:
        public function setHandler($host$user$pass$data) {
            
            
$this->host $host;
            
$this->user $user;
            
$this->pass $pass;
            
$this->data $data;
            
            return 
$this;
            
        } 
I think this is pretty self-explenatory.
The end:
PHP Code:
return $this
..makes it possible to CHAIN the functions later when we call them and that just looks so awesome.

PHP Code:
        public function connect() {
            
            @
mysql_connect($this->host$this->user$this->pass) or die("Could not connect to the database.<br /> " .mysql_error());
            
            return 
$this;
            
        } 
I think this is pretty straight forward aswell. We return $this here aswell.

PHP Code:
        public function select() {
            
            @
mysql_select_db($this->data) or die("Could not select database.");
            
            return 
$this;
            
        } 
I'm not gonna say anything..

PHP Code:
        public function disconnect() {
            
            @
mysql_close() or die("Could not close database connection. Perhaps because the connection isn't opened.");
            
        } 
PHP Code:
        public function query($query) {
            
            
$result mysql_query($query);
            
            return 
$result;
            
        } 
Here's some new stuff, but still really basic. If you're even reading this guide, about classes and interfaces, you should definitely know how to make a mysql query!!

PHP Code:
        public function fetch($sql) {
            
            
$array mysql_fetch_array($sqlMYSQL_ASSOC);
            
            return 
$array;
            
        } 
... Fetches an array

PHP Code:
        public function secure($string) {
            
            
$secure mysql_real_escape_string($string);
            
            return 
$secure;
                        
        } 
Secures a string from possible mysql injections.

PHP Code:
        public function setTable($field$value) {
            
            
$this->table[$field] = $value;
            
        }
        
        public function 
setCol($field$value) {
            
            
$this->col[$field] = $value;
            
        } 
These are our 2 magic functions
The explenation comes later..

The whole class:
PHP Code:
/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/

    
class DBmysql implements iDB {
        
        private 
$host;
        private 
$user;
        private 
$pass;
        private 
$data;
        public 
$table = array();
        public 
$col = array();
        
        
        public function 
setHandler($host$user$pass$data) {
            
            
$this->host $host;
            
$this->user $user;
            
$this->pass $pass;
            
$this->data $data;
            
            return 
$this;
            
        }
        
        public function 
connect() {
            
            @
mysql_connect($this->host$this->user$this->pass) or die("Could not connect to the database.<br /> " .mysql_error());
            
            return 
$this;
            
        }
        
        public function 
select() {
            
            @
mysql_select_db($this->data) or die("Could not select database.");
            
            return 
$this;
            
        }
        
        public function 
disconnect() {
            
            @
mysql_close() or die("Could not close database connection. Perhaps because the connect isn't opened.");
            
        }
        
        public function 
query($query) {
            
            
$result mysql_query($query);
            
            return 
$result;
            
        }
        
        public function 
fetch($sql) {
            
            
$array mysql_fetch_array($sql);
            
            return 
$array;
            
        }
            
        public function 
secure($string) {
            
            
$escapedstring mysql_real_escape_string($string);
            
$secure stripslashes($escapedstring);
            
            return 
$secure;
                        
        }
        
        public function 
setTable($field$value) {
            
            
$this->table[$field] = $value;
            
        }
        
        public function 
setCol($field$value) {
            
            
$this->col[$field] = $value;
            
        }
        
        
    } 
Did you notice btw, that the table variable, and the col variable are public eventhough I said in my other guide that you should never have public variables??
This makes it really sweet for you when you write your plugins later So trust me on this one :P




Section 3: The database factory

So onto the DB factory!
This is the.. ultimate thing. It makes it so easy to include the classes it's unbelievable.. :P

We name the file DB.php and the first thing we have in it is an autoload function..

PHP Code:
    function __autoload($classname) {
        
        include_once(
$classname '.php');
        
    } 
This makes it so that whenever you call ..
PHP Code:
$object = new DBmysql(); 
.. it autoincludes DBmysql file so you can create the object. You don't have to include the file in the beginning or anything! Magic!

Secondly, we will have the factory class:

PHP Code:
    class DB {
        
        public static 
$DB;

        public static function 
getInstance($type) {
        
            if(!
is_object(self::$DB)) {
                
                
$type strtolower($type);
                
$type 'DB'.$type;
                    
                
self::$DB = new $type();
                
            }
            
               return 
self::$DB;
    
        }

    } 
So what the **** is this?
Static??!?!

Yah! It's something awesome, and sweet, and.. completely madness
Static means that you can use it, without instance the DB class.

Instead of writing:
PHP Code:
$db = new DB();
echo 
$db->DB
You can just do this:
PHP Code:
echo DB::$DB
Not that you would want to echo the DB object(it's a variable, but contains an object if you called the getInstance function) but still you get the point.

So what does this getInstance do?
Well, first we check if the variable $DB is an object already, and if it's not, we do the things inside the bracket.
Also note, that when dealing with static variables or functions, we have to use self:: instead of $this.

Actually, I think this function is pretty easy to understand.
What happens is that you include DB.php
Then:
PHP Code:
$database DB::getInstance('mysql'); 
.. and it tries to include DBmysql.php, create an instance of it, and return the object.
Now don't tell me that this ain't neat?

NOTE: iDB.php, DB.php and DBmysql.php should be placed in the classes folder!




Section 4: The config and classes files

So the configuration file will ofcourse contain alot more when you have your plugins written, but right now we'll just include the basic stuff.
This is my configuration file:

PHP Code:
/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/

    
$tanaxia['config']['database']['host'] = 'localhost';    // Database host
    
$tanaxia['config']['database']['user'] = 'root';        // Database user
    
$tanaxia['config']['database']['pass'] = '';            // Database pass
    
$tanaxia['config']['database']['data'] = 'slutuppgift'// Database name
    
$tanaxia['config']['database']['type'] = 'mysql';        // Database type
    
    
session_start();
    include(
'classes.php'); 
Yeh, erh.. I got kinda long variables+arrays there, but that's just so I could easially see what it is.
It's the $tanaxia variable(in this case for me it means that it's belonging to the core), and it's the ['config'] array, which means for me that it's
a setting for the core. The next array ['database'], means that it's a database setting, and then the next is defining what setting.

I then start the session, and include classes.php


Onto the classes file; this is what makes or breaks the script. Here we start all the classes, AND we use the setCol and setTable functions of the database class.
This is the classes file:
PHP Code:
/**
||||||||||||||||||||||||||||||||||||||||||
|||| @author Tanax
|||| @copyright 2008
||||||||||||||||||||||||||||||||||||||||||
**/

    
include('classes/DB.php');
    
    
$tanaxia['database'] = DB::getInstance($tanaxia['config']['database']['type']);    
    
$tanaxia['database']->setHandler(
                
                        
$tanaxia['config']['database']['host'],
                        
$tanaxia['config']['database']['user'],
                        
$tanaxia['config']['database']['pass'],
                        
$tanaxia['config']['database']['data']
                        
                        )
                        ->
connect()
                        ->
select();
                        

        
    
//$tanaxia['database']->setTable('news', 'news');
    //$tanaxia['database']->setCol('news_id', 'news_id');
    //$tanaxia['database']->setCol('news_publish', 'news_publish'); 
So, we include our DB factory.
Then we create the database, based on the type settings in our config file.

After that we set the handler with all the data provided from the config file, and then directly we chain the next function(remember the chain I talked about?) and connect to
the host, and then select the database.

That's really everything we've done now.

The things that are commented describes how to use the setTable.

The good things with that, is that later when you use the db object in the plugins(for example news plugin), you want to insert values into different columns in the database.
An example would be this:

PHP Code:
    class news {
        
        private 
$db;
        private 
$newsid;
        
        public function 
__construct($db) {
            
            
$this->db $db;
            
        }
        
        public function 
getNewsbyID($id) {
                
            if(!
is_numeric($id)) {
                    
                return 
false;
                    
            }
                
            else {
                    
                
$sql sprintf("    SELECT
                                        *
                                    FROM
                                        `%s`
                                    WHERE
                                        `%s` = '%s'
                                    AND
                                        `%s` != 0
                                    LIMIT 1"
,
                                        
                                    
$this->db->table['news'],
                                    
$this->db->col['news_id'],
                                    
$id,
                                    
$this->db->col['news_publish']);
                                        
                
$query $this->db->query($sql);
                    
                if(!
$query) {
                        
                    return 
false;
                        
                }
                    
                else {
                        
                    unset(
$this->newsid);
                    
$this->newsid $this->db->fetch($query);
                    return 
$this->newsid;
                        
                }
                    
            }
            
        }
        
        
    } 
As you see, we call the table news. But what if you decide to rename the table in your database and you've hardprinted `news` into the query?
Then you need to enter your class and change EVERYTHING to match the new name. And that kinda stinks.

So let's say you change the news table name to "articles".

Then you just enter your classes.php file, and change this line:
PHP Code:
$tanaxia['database']->setTable('news''news'); 
to this:
PHP Code:
$tanaxia['database']->setTable('news''articles'); 
Now, even if we in the class call the table "news", it will assosciate with "articles", so it's really easy and manageable.

NOTE: Both config.php and classes.php goes into your includes folder!

So the structure we have, looks like this right now:

Code:
www
- test
- - includes
- - - config.php
- - - classes.php
- - - classes
- - - - DB.php
- - - - iDB.php
- - - - DBmysql.php


This is everything right now! Part 2 will be about plugins



Reply With Quote

Donate to remove ads.
(#2)
Old
Vivacity is Offline
Site n00b.. (A leecher if I've been here for more than a month and can't earn 5 rep)
Rep Power: 1
Reputation: 1
Vivacity is an unknown quantity at this point
 
Posts: 50
Join Date: Apr 2008
04-23-2008

nice guide, its helpful, thanks
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On



Powered by vBulletin® Version 3.7.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0
vBulletin Skin developed by: vBStyles.com


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218