I'm a little new to object oriented PHP and MVC, so I really need help.
I have a MVC style folder structure with subfolders in the file system
- eg. view/classes/subfolder/classname.php
I use mod_rewrite for human-friendly URLs like /classname
or /foldername/calssname
, which are then passed to the page loader as an underscore of shared values.
- eg. foldername_classname
// Page Loader File
require_once ($ _ SERVER ['DOCUMENT_ROOT']. '/ local / classLoader.php');
session_start ();
$ page = new $ _REQUEST ['page'];
I previously used the [if / else if / else] block to test in every possible folder, but this seems inefficient, so I'm looking for the best way to find the autoloader in many different places.
Here is my last glitch that none of the requested classes can be found and simply throws an exception for each, ending with a fatal error !:
function classToPath ($ class) {
$ path = str_replace ('_', '/', $ class). '.php';
return $ path;
}
function autoloadController ($ class) {
echo 'LoadController'. '
';
$ root = '/ controller / classes /';
$ pathtoclass = $ root.classToPath ($ class);
try {
if (file_exists ($ pathtoclass)) require_once ($ pathtoclass);
else throw new Exception ('Cannot load controller'. $ class);
} catch (Exception $ e) {
echo 'Controller exception:'. $ e-> getMessage (). "
";
}
}
function autoloadModel ($ class) {
echo 'LoadModel'. '
';
$ root = '/ model / classes /';
$ pathtoclass = $ root.classToPath ($ class);
try {
if (file_exists ($ pathtoclass)) require_once ($ pathtoclass);
else throw new Exception ('Cannot load model'. $ class);
} catch (Exception $ e) {
echo 'Model exception:'. $ e-> getMessage (). "
";
}
}
function autoloadView ($ class) {
echo 'LoadView'. '
';
$ root = '/ view / classes /';
$ pathtoclass = $ root.classToPath ($ class);
try {
if (file_exists ($ pathtoclass)) require_once ($ pathtoclass);
else throw new Exception ('Cannot load view'. $ class);
} catch (Exception $ e) {
echo 'View exception:'. $ e-> getMessage (). "
";
}
}
spl_autoload_register ('autoloadController');
spl_autoload_register ('autoloadModel');
spl_autoload_register ('autoloadView');
I was also interested to know how the URL should work for folder / class mapping:
- i.e. URL:
/foldername/classname
mod_rewritten to
foldername_classname
;
with the class file name
classname.php
in the
foldername
folder;
and php
class foldername_classname extends another_class { etc.
Is this the correct method?
source share