Announcement

Collapse
No announcement yet.

Object oriented programming in practice - An example - PHP

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Object oriented programming in practice - An example - PHP

    How does object oriented programming fit into application development?

    Simply put, object oriented programming allows us to create large (and often complex) applications without having the mess that is often associated with unorganised, incoherent procedural code (although of course it is possible to structure application logic into different segments using just procedural programming - for example, with the use of functions common to most programming languages).

    What is "procedural" programming?

    Procedural is the term used to refer when logic is laid out in a procedure - line-for-line - with the use of functions in order to wrap logic (or application functionality, in other words) to use in many instances in our application.

    Object oriented programming extends this model, by adding interesting and useful conceptual features to make it easier to separate very important application logic from the arbitary PHP code here and there. Of course, I'm using PHP as an example. Even though PHP comes with an extensive framework of object oriented programming features, you will still be using procedural programming, for example in arbitary PHP files or the PHP files that contain the HTML code and output to be displayed to the end user.

    An example use of object oriented programming in an application I am developing is shown below; the application code below is part of a URL shortener script that will be released as a tutorial on our blog in a short while. The script itself uses features such as PHP Data Objects and other useful features. PHP Data Objects (or PDO for short) is an object oriented way of connecting to a variety of database systems, such as MySQL.

    The code below:

    PHP Code:
    <?php
        
    include("database.php");
        
        class 
    Input
            
    {    
                public 
    $db;
        
                public function 
    __construct()
                {
                    
    $conn = new Database();
                    
    $this->db $conn->connect();
                }
                
                public function 
    unique_id_to_url($uid)
                {
                    
    $suid $this->db->quote($uid);
                    
    $check_execute $this->db->query("SELECT * FROM urls WHERE unique_id = $suid LIMIT 1");
                    if(
    $check_execute->rowCount() == 1)
                    {
                        return 
    $check_execute->row // under construction here
                    
    }
                }
            
                public function 
    check_url_exists($url)
                {
                    
    // check the URL SECURELY
                    
    $surl $this->db->quote($url);
                    
    $check_execute $this->db->query("SELECT url FROM urls WHERE url = $surl");
                    if(
    $check_execute->rowCount() == 1)
                    {
                        return 
    1;
                    }
                    else
                    {
                        return 
    0;
                    }
                }
                
                public function 
    add_url_to_db($url,$unique)
                {
                    
    $ip $_SERVER['REMOTE_ADDR'];
                    
    $surl $this->db->quote($url);
                    
    $sunique $this->db->quote($unique);
                    
    $time time();
                    
    $ins_execute $this->db->exec("INSERT INTO urls (url,unique_id,submitter_ip_address,submitted_time) VALUES ($surl,$sunique,'$ip','$time')");
                    if(
    $ins_execute)
                    {
                        return 
    $ins_execute;
                    }
                    else
                    {
                        return 
    0;
                    }
                }
            
                public function 
    check_and_submit_url($url)
                {
                    if(
    $url)
                    {
                        if(!
    filter_var($url,FILTER_VALIDATE_URL))
                        {
                            return 
    'check_and_submit_url_invalid_url';
                        }
                        elseif(
    $this->check_url_exists($url))
                        {
                            return 
    'check_and_submit_url_exists';
                        }
                        else
                        {
                            
    // how many current rows?
                            
    $row_exec $this->db->query("SELECT * FROM urls ORDER BY url_id DESC");
                            
    $row_exec_count $row_exec->rowCount();
                            
    $unique_id md5(uniqid(time(),TRUE));
                            
    $unique_id_substr substr($unique_id,0,10);
                            
    $unique_id_final $unique_id_substr . ($row_exec_count 1);
                            if(
    $this->add_url_to_db($url,$unique_id_final))
                            {
                                return 
    'check_and_submit_url_success';
                            }
                            else
                            {
                                return 
    'check_and_submit_url_ultimate_failure';
                            }
                        }
                    }
                }
        }
    ?>
    You won't understand everything, but you can probably understand the conceptual logistics of what is occurring. A class is a wrapper for application logic, kind of like an ordinary function is. The functions residing within the class are technically called methods in object oriented programming, but at least in PHP, you can call them functions too. However, to differentiate ordinary functions to class functions, you may wish to call them methods.

    In order to use a particular method within the class, you have to first allocate the class into computer memory. At the moment, it is simply like a computer application being stored on your computer, but not being run. The formal term for this is creating an instance of the class (or instantiation). To create an instance of a class, you use the new keyword:

    PHP Code:
    <?php
    $input 
    = new Input();
    ?>
    In order to execute one of the methods, you use the arrow operator:

    PHP Code:
    <?php
    $input 
    = new Input();
    $check_url $input->check_url_and_submit();

    if(
    $check_url == 'check_and_submit_url_success')
    {
    echo 
    "URL added.";
    }
    ?>
    You will notice in the class there is also a method called __construct. This is not a unique method of my application. If the __construct keyword is used as the name of a function, it becomes the class constructor, and any code within the constructor method is executed as soon as the class is instantiated. The difference is if you had the logic within the check_url_and_submit() method in the constructor, you would not need to execute that separate method. Simply instantiating the class as shown below would execute the logic within the constructor method:

    PHP Code:
    <?php
    $input 
    = new Input(); // execute any applicable code within the constructor method
    ?>
    And as you can see, the constructor method contains the following code:

    PHP Code:
    public function __construct()
    {
        
    $conn = new Database();
        
    $this->db $conn->connect();

    As you can see, the database connection is being established within the constructor. I could have a separate connect_database() method for this, but that would be inconvenient wouldn't it?

    Speaking of the database connection, you can see at the top there is an include() function being used, to include the database.php file. This contains the logic that connects to the MySQL database. The code for database.php is shown below:

    PHP Code:
    <?php
        
    class Database
        
    {
            
    // create a new database connection using PHP Data Objects (PDO)        
            
    public function connect()
            {
                try
                {
                    return new 
    PDO("mysql:dbname=cpanel_username_db_name;host=localhost","cpanel_username_db_user","pw_here");
                }
                catch(
    PDOException $error// $error returns error from PDOException class
                
    {
                    echo 
    "<p><b>Database connection error.</b></p>";
                    echo 
    "<p>".$error->getMessage()."</p>";
                    die();
                }
                
            }
        }
    ?>
    Hope this helps.

    Other useful tutorials:

    http://forums.eukhost.com/f50/access...utorial-16898/
Working...
X