10.2. Building a Comments Class

Separating your commenting system separate from the rest of your blog makes it easier to maintain and extend in the future; you'll leverage the object-oriented approach you learned about in Chapter 8 to implement this feature.

Begin by creating a new file that will contain the class. Call this file comments.inc.php, and store it in the inc folder in the simple_blog project (full path: /xampp/htdocs/simple_blog/inc/comments.inc.php).

Once you create the file, you need to declare the class and a constructor for it. This class must be able to read and write from the database, so you need to include the database information stored in db.inc.php.

Your class needs a property to hold the database variable. Your class also needs to open a database connection in the constructor that you store in the aforementioned property, which you will call $db.

Next, include the database info, create the class, and define a property and constructor for Comments by adding the code in bold to your newly created comments.inc.php:

<?php

include_once 'db.inc.php';

class Comments
{
    // Our database connection
    public $db;

    // Upon class instantiation, open a database connection
    public function __construct()
    {
        // Open a database connection and store it
        $this->db = new PDO(DB_INFO, DB_USER, DB_PASS);
    }
}

?>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.202.209