I'm trying to create a system that would autoload classes when they're needed.
This is my folder structure
| index.php
| app
| - app.php
| - core
| -- core.php
| -- helpers
| --- htmlhelper.php
where index.php
is the bootstrap file, core.php
is the core file I'd like to extend and all the classes in the helpers folder would contain classes I'd like to autoload.
Since autoloading on my own is a fairly new thing for me I'm pretty confused on how to do it. I can autoload the core file, but I cannot seem to figure out how to autoload the helper classes.
This is the code I have so far:
index.php
require_once('app/app.php');
$app = new App();
$app->display();
app.php
use App\Core\Core as Core;
// autoload
spl_autoload_extensions(".php");
spl_autoload_register();
class App{
function __construct(){
//Core::addStyle('/file/css/foo1.css');
Core::foo();
}
public function display(){
Core::getStyles();
}
}
core.php
namespace App\Core;
// dependancies
use App\Core\Helpers\HtmlHelper as Helper;
// autoload
spl_autoload_extensions(".php");
spl_autoload_register();
class Core
{
function foo(){
var_dump('bar');
}
}
htmlhelper.php
namespace App\Core\Helpers;
class HtmlHelper extends Core{
protected $styles;
protected $scripts;
public static function addStyle($data){
if(is_array($data)){
$this->styles = array_merge($this->styles, $data);
}else{
$this->styles[] = $data;
}
}
public static function getStyles(){
var_dump($this->styles);
}
}
With the code I have now the core
class gets autoloaded fine, and I can call the foo()
method, but the htmlhelper
class won't get loaded. I know this because PHP throws an error that getStyles()
is undefined.
I'm doing this to achieve one exit point for the core functions of the application, but separate the code in different files.
Ideally I'd like to load all classes in the helper folder automatically and not have to put a block of use ..
definitions, if that's doable.
I think that the lack of knowledge about php namespacing is my biggest flaw at this point.
I can't seem to find any good sources that would fully explain how would I do these things in a simple language for dummies.