I have to create some APIs for a online game and I decided to learn to use namespaces correctly.
I used the factory pattern, then the loadModule
method checks if in the Modules folder there is a class named $module and then it return the object.
The folders are synchronized with the namespaces.
The main class Metin2.class.php
:
<?php
namespace Metin2;
use mysqli;
use \Metin2\Utilities as Utilities;
require_once("config.php");
require_once(UTILITIES_PATH . "Autoloader.class.php");
class Metin2
{
public $db;
public function __construct(mysqli $database)
{
spl_autoload_register("Metin2\\Utilities\\Autoloader::loadModel");
try {
if(!$database) throw new Exceptions\Metin2Exception("The database instance is not a valid instance");
$this->db = new Utilities\Database($database);
} catch (Exceptions\Metin2Exception $e) {
echo $e->errorMessage();
}
}
public function loadModule($module)
{
$m = "\\Metin2\\Modules\\" . $module;
return new $m;
}
}
Autoloader class:
<?php
namespace Metin2\Utilities;
class Autoloader {
public static function loadModel($class){
$class = str_replace("\\","/",$class);
$class = explode("/",$class);
if($class[0] == "Metin2")unset($class[0]);
$class = implode("/",$class);
$path = ROOT_PATH.$class.".class.php";
if(file_exists($path)){
require_once($path);
}
}
}
An example of a module:
<?php
namespace Metin2\Modules;
class Testdb {
public $db;
public function __construct(){
$this->db = \Metin2\Utilities\Database::getInstance();
print_r($this->db->getOne("account"));
}
}
Everything works well, but I want to know if there are any things I did wrong or if there are things I can do better.