Search code examples
phpoopmysqlipear

OOP php5 structure


I have been trying to make OOP PHP5 code. But I think my attempts are clumsy. These are my questions:

  • Is their a better, more leaner way to include database config information?
  • Can I somehow get around having to declare $db = new Db() in every function I make?
  • Should I use PEAR as database abstraction layer instead of Mysqli_database.php?

Mysqli_database.php

<?php
class Db {
    private $connection;

    private function open_connection() {
        if (file_exists('config.inc.php')) {
            require('config.inc.php');
        } else {
            require('../config.inc.php');
        }
        try
        {
            $this->connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
        }
        catch (Exception $e)
        {
            throw $e;
        }
    }
    private function close_connection() {
        try
        {
            mysqli_close($this->connection);
        }
        catch (Exception $e)
        {
            throw $e;
        }
    }
    public function query($query) {
        try
        {
            $this->open_connection();
            $result = mysqli_query($this->connection,$query);
            return $result;
        }
        catch (Exception $e)
        {
            throw $e;
        }
        $this->close_connection();
    }
    public function fetchArray($query) {
        $row = mysqli_fetch_assoc($query);
        return $row;
    }
    public function count_rows($query) {
        $row = mysqli_num_rows($query);
        return $row;
    }
    public function rows_affected() {
        $row = mysqli_affected_rows($this->connection);
        return $row;
    }
    public function created_id() {
        $row = mysqli_insert_id($this->connection);
        return $row;
    }
}
?>

Test_data.php

<?php
class Test_data {
    public function show_text() {
        $db = new Db();
        $sql = $db->query("SELECT * FROM test_table");
        $row = $db->fetchArray($sql);
        echo 'This is the output: '.$row['text'];
    }
}
?>

config.inc.php

<?php
$dbname     = 'database_name';
$dbhost     = 'localhost';
$dbuser     = 'database_user';
$dbpass     = 'database_password';
?>

includes.php

<?php
require_once('config.inc.php');
require_once('Mysqli_database.php');
$db = new Db();
$test_data = new Test_data();
?>

index.php

<?php
require_once('includes.php');
$test_data->show_text();
?>

Solution

  • The config information is a matter of taste. But it would be better stored in a config object, and retreived in a more OO way then including global variables from another file.

    You can get around creating a new object by using the singleton pattern.

    The more abstracted layer you choose, the easier it will be to move from one database to another. You can also have a look at PDO.