How do I autoload classes with a file name other than the class name?
I saw them
How do I autoload a class with a different filename? PHP
Load a class with a different name than the one passed to the autoloader as an argument
I can change, but in my MV * framework I have:
/models
customer.class.php
order.class.php
/controllers
customer.controller.php
order.controller.php
/views
...
In actual classes, they
class CustomerController {}
class OrderController{}
class CustomerModel{}
class OrderModel{}
I tried to match the names. If I don't put the class name suffix (Controller, Model) then I cannot load the class because this is an update.
If I keep my class names the autoloading fails because it will look for a class file named
CustomerController
when the filename is valid,
customer.controller.php
I am the only way (in no order):
- use create_alias
- rename my files (customer.model.php to customermodel.php)
- rename my classes
- use regular expressions
- use a boot file with included files (
include
,require_once
etc.)
?
Sample code,
function model_autoloader($class) {
include MODEL_PATH . $class . '.model.php';
}
spl_autoload_register('model_autoloader');
I seem to need to rename the files,
http://www.php-fig.org/psr/psr-4/
"The term class name matches a file name ending in .php. The file name MUST match the trailing class name case."
source to share
It seems to me that it might have to do with some basic string manipulation and some conventions.
define('CLASS_PATH_ROOT', '/');
function splitCamelCase($str) {
return preg_split('/(?<=\\w)(?=[A-Z])/', $str);
}
function makeFileName($segments) {
if(count($segments) === 1) { // a "model"
return CLASS_PATH_ROOT . 'models/' . strtolower($segments[0]) . '.php';
}
// else get type/folder name from last segment
$type = strtolower(array_pop($segments));
if($type === 'controller') {
$folderName = 'controllers';
}
else {
$folderName = $type;
}
$fileName = strtolower(join($segments, '.'));
return CLASS_PATH_ROOT . $folderName . '/' . $fileName . '.' . $type . '.php';
}
$classNames = array('Customer', 'CustomerController');
foreach($classNames as $className) {
$parts = splitCamelCase($className);
$fileName = makeFileName($parts);
echo $className . ' -> '. $fileName . PHP_EOL;
}
Output signal
Client -> /models/customer.php
CustomerController -> /controllers/customer.controller.php
Now you need to use makeFileName
inside the autoloader function.
I myself am strongly against such things. I would use namespaces and file names that reflect the namespace and class name. I would also use Composer .
(I found it splitCamelCase
here .)
source to share