One answer to this question is
Creating a single library which all modules can access.
Create you own php classes. Add them in you own custom library folder inside /libraries of your joomla installation.
Classes in a folder that follow a naming convention can be registered collectively with JLoader::discover() method. The discover method looks at the file names in a folder and registers classes based on those names.
Then you will need a loader to load your library class files. This can be done via
- Discovering your library
// Register all files in the /libraries/mylib folder as classes with a name like: MyLib
JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib');
- Prefixing your class names to make them discoverable easily.
// Tell the auto-loader to look for classes starting with "Mylib" in a specific folder.
JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');
For single database object on all modules, your database class should follow singleton pattern.
Singletons are designed to ensure there is a single (hence the name singleton) class instance and that is global point of access for it, along with this single instance we have global access and lazy initialization.
A example of DB class using singleton pattern here:
<?php
/**
* PDO Singleton Class v.1.0
*/
class DB {
protected static $instance;
protected function __construct() {}
public static function getInstance() {
if(empty(self::$instance)) {
$db_info = array(
"db_host" => "localhost",
"db_port" => "3306",
"db_user" => "user",
"db_pass" => "pass",
"db_name" => "ftonato",
"db_charset" => "UTF-8");
try {
self::$instance = new PDO("mysql:host=".$db_info['db_host'].';port='.$db_info['db_port'].';dbname='.$db_info['db_name'], $db_info['db_user'], $db_info['db_pass']);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
self::$instance->query('SET NAMES utf8');
self::$instance->query('SET CHARACTER SET utf8');
} catch(PDOException $error) {
echo $error->getMessage();
}
}
return self::$instance;
}
public static function setCharsetEncoding() {
if (self::$instance == null) {
self::connect();
}
self::$instance->exec(
"SET NAMES 'utf8';
SET character_set_connection=utf8;
SET character_set_client=utf8;
SET character_set_results=utf8");
}
}
?>
It can now be used as follows:
<?php
require_once ('database.class.php');
try {
$db = DB::getInstance();
DB::setCharsetEncoding();
$sqlExample = 'SELECT * FROM users WHERE _id = 1';
$stm = $db->prepare($sqlExample);
$stm->execute();
return $stm->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
print $e->getMessage();
}