[Tutorial] PHP How to organize your classes | Part 1 menu

User Tag List

Results 1 to 2 of 2
  1. #1
    Tanax's Avatar Active Member
    Reputation
    53
    Join Date
    Jan 2007
    Posts
    239
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [Tutorial] PHP How to organize your classes | Part 1


    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

    Hm.

    [Tutorial] PHP How to organize your classes | Part 1
  2. #2
    Vivacity's Avatar Member
    Reputation
    1
    Join Date
    Apr 2008
    Posts
    47
    Thanks G/R
    0/0
    Trade Feedback
    0 (0%)
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    nice guide, its helpful, thanks

Similar Threads

  1. [Tutorial] PHP Pagination class
    By Tanax in forum Programming
    Replies: 5
    Last Post: 09-01-2015, 04:50 AM
  2. How to Become Better at Your Class
    By mcspunk14 in forum World of Warcraft Guides
    Replies: 9
    Last Post: 07-05-2008, 01:09 AM
  3. Video Tutorial on How to change your realmlist
    By Mellexx in forum World of Warcraft Guides
    Replies: 16
    Last Post: 05-27-2008, 01:38 PM
  4. [Guide]How To Coustom Your Chracter Class
    By EatUrBrains in forum WoW EMU Guides & Tutorials
    Replies: 4
    Last Post: 11-19-2007, 03:55 AM
  5. [How to] Choosing your class and Race!
    By galathius in forum World of Warcraft Guides
    Replies: 17
    Last Post: 10-30-2007, 11:59 AM
All times are GMT -5. The time now is 04:14 AM. Powered by vBulletin® Version 4.2.3
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved. User Alert System provided by Advanced User Tagging (Pro) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
Digital Point modules: Sphinx-based search