I have two codes, the first one uses spl_autoload_register
and the other does not, however the second one loads "automatically the class" as well.
With spl_autoload_register
- Uses namespaces to split MVC
- You can create multiple levels of folders following the idea of PSR-4
- Controllers and Models can have the same name as each one is within a different namespace.
Code:
spl_autoload_register(function ($class)
{
$np = explode('\', $class);
$base = strtolower($np[0]);
switch ($base) {
case 'controller':
case 'model':
$base = 'application/' . $base . 's';
break;
default:
return NULL;
}
array_shift($np);
$relative_class = strtolower(implode('/', $np));
$file = './' . $base . '/' . $relative_class . '.php';
/*
* resulta em algo como:
* ./application/controllers/foo/test/user.php
* ./application/models/foo/abc/user.php
*/
if (is_file($file)) {
require_once $file;
}
});
Calling an action from a controller:
$controller = new \Controller\foo\test\user;
$controller->profile();
Calling a model:
$model = new \Model\foo\test\user;
With methods
- Do not use namespaces
- "Eventually" may be easier to understand / use than the previous one
- Controllers and Models can not have the same name, but it's no problem since we can use prefixes
- Supports subfolders.
Code:
<?php
class App
{
static private function prepare($path)
{
$fp = explode('.', $path);
return array(
'name' => end($fp),
'path' => implode('/', $fp)
);
}
static public function model($name)
{
$data = self::prepare($name);
if (is_file($data['path'])) {
require_once './application/models/' . $data['path'] . '.php';
}
return new $data['name'];
}
static public function action($name, $action)
{
$data = self::prepare($name);
if (is_file($data['path'])) {
require_once './application/controllers/' . $data['path'] . '.php';
}
$controller = new $data['name'];
$controller->$action;
}
}
Calling an action from a controller:
App::action('foo.test.user', 'profile');
Calling a model:
$model = App::model('foo.abc.user');
My question is, should I use the simplest way without namespaces and spl_autoload
or not? How can I work on or improve these codes to make it easier for the final developer to use?