Simple PHP class that allows for a more structured manner of importing classes.
PackageManager.php:
<?php
class PackageManager {
const PACKAGE_BASE = "./";
private $path;
function __construct($path) {
$path = str_replace(".", "/", $path);
$this->path = PackageManager::PACKAGE_BASE . (substr($path, -1, 1) == "/" ? $path : $path . "/");
}
function import($file) {
if ($file == "*") {
foreach(glob($this->path . "*") as $class) {
require_once $this->path . $class;
}
} else {
$classes = explode(",", $file);
foreach($classes as $class) {
$class = trim($class);
$class = (substr($class, -4, 4) == ".php"_ ? $class : $class . ".php";
require_once $this->path . $class or
throw new PackageManagerException("Class: {$class} was not found in {$this->path}");
}
}
}
}
class PackageManagerException extends Exception { }
function from($path) {
return new PackageManager($path);
}
?>
if you had the following file structure:
PackageManager.php
index.php
app/
blog/
Posts.php
Feeds.php
comments/
Comments.php
core/
lib/
DB.php
Template.php
Urls.php
You could include any of the following (or every) in index.php:
from("app.blog")->import("Posts, Feeds");
from("app.blog.comments")->import("Comments.php");
from("core.lib")->import("*");
from("core.lib")->import("DB, Urls");
try {
from("core.lib")->import("Unknown");
} catch(PackageManagerException $e) {
echo $e->getMessage();
}