Search code examples
phpclassmethodscall

calling PHP classes from files


I'm building a website for a project I'm currently working on. I want to initialize a class called PDOConfig in a separate file which fills an array with database details. However I get an error saying Class PDOConfig not found. To get a better understanding of what I mean here are the pages in question:

index.php

<?php

// Start the output buffer and start the session
ob_start();
session_start();
// init.php will include all the required core libraries
include_once('includes/scripts/php/init.php');
?>

<!-- html code -->

<?php
ob_end_flush();
?>

includes/scripts/php/init.php

<?php
// init.php
// This file includes all the core libraries and, if required, customer and admin libraries.

#TODO: Include core libraries
require('libCore/vars.php');
require('libCore/db.php');
require('libCore/pages.php');
require('libCore/catalogue.php');

#TODO: Check if customer has logged in. If so include customer libraries.

#TODO: Check if a member of staff has logged in. If so include admin libraries.

#TODO: Log File Variables
$dblogfile = logs/db_log.txt';
?>

includes/scripts/php/libCore/vars.php

<?php
// vars.php
// This file contains all of the site variables.

# Database Variables
$db_conf = new PDOConfig();
$db_conf->write('dsn.host', 'localhost');
$db_conf->write('db.username', '/*Username Here*/');
$db_conf->write('db.password', '/*Password Here*/');
$db_conf->write('dsn.dbname', 'A1Newsagents');
$db_conf->write('dsn.driver', 'sqlsrv');
$db_conf->write('dsn.charset', 'utf8');

#TODO: Form Variables

#TODO: Page Title Variables


?>

includes/scripts/php/libCore/db.php

<?php
// libCore/db.php
// This file contains all of the classes and functions required for database interaction.

class PDOConfig
{
    // This class sets up an array that stores the configuration for the DSN and db username/password
    static $confarray;

    public static function read($conf_name)
    {
        return self::$confarray[$conf_name];
    }

    public static function write($conf_name, $conf_value)
    {
        self::$confarray[$conf_name] = $conf_value;
    }
}

class DBCore
{
    // This class sets up the database connection and controls database functionality
    public $dbc;
    private static $dbinst;

    private function __construct()
    {
        // Build DSN
        $dsn = PDOConfig::read('dsn.driver') . ':Server=' . PDOConfig::read('dsn.host') . ';Database=' . PDOConfig::read('dsn.dbname');

        // Get db username and password
        $dbuser = PDOConfig::read('db.username');
        $dbpass = PDOConfig::read('db.password');

        // Set the error mode to EXCEPTION, turn off PREPARE EMULATION and set the fetch mode to FETCH_ASSOC
        $dbopts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

        // Start a new databse connection instance
        $this->dbc = new PDO($dsn, $dbuser, $dbpass/*, $dbopts*/);
    }

    public static function DBInstance()
    {
        if (!isset(self::$dbinst))
        {
            $dbobject = __CLASS__;
            self::$dbinst = new $dbobject;
        }
        return self::$dbinst;
    }
}
?>

Is there a way I can make this work without having to include db.php in every file? I have seen something about using something called "namespaces" to do this however I think I need to get a better grasp of classes first as I'm still very amateur at this stuff. Thanks


Solution

  • It sounds as though the the problem is with the way you are using multiple PHP include() / require(), pointing to the wrong folder. When you use either of those functions, the files that you include essentially 'copy' their contents into the file that is including them.

    First, you are including includes/scripts/php/init.php on index.php. The contents of init.php are essentially written into index.php. Thus, when you use require('libCore/vars.php'); (inside init.php), the require() is relative to index.php (not init.php). Because index.php is at the root, the require() looks in [ROOT]/libCore/vars.php, instead of [ROOT]/includes/scripts/php/libCore/vars.php.

    To resolve this, you should make includes/scripts/php/init.php require() from includes/scripts/php/, or better yet, use root-relative URLs (note the leading backslash):

    `require('/libCore/vars.php');`
    

    Hope this helps! :)