On working PHP MVC, on CONTROLLER folder i have a files controller, but inside has folders that must called controller inside folders.
Has anyone better way and nicely code implementation of these below?
I’m working on this way but I’m not sure is that best way calling controller?
/*
STRUCTURE OF DIR FILES: controllers:
a/b/c/file.php
a/b/c <-- IS DIRECTORY
a/b/c <-- IS FILE
*/
$uri_result = false;
$controller_called = false;
/* called controllers */
$uri_segments[0] = 'a';
$uri_segments[1] = 'b';
$uri_segments[2] = 'c';
#$uri_segments[3] = 'file.php';
/* end called controllers */
$counted = count($uri_segments);
$filled = array();
$i = 0;
do {
if ($i < $counted)
{
$z[] = $uri_segments[$i];
$ez = implode('/', $z);
}
if (file_exists($ez))
{
$uri_result = $ez;
$controller_called = $z[$i];
}
++$i;
} while ($i < $counted);
var_dump($uri_result,$controller_called);
/* RESULTS:
If called $uri_segments[0] to uri_segments[3]
string(14) "a/b/c/file.php" string(8) "file.php"
If called $uri_segments[0] to uri_segments[2]
string(5) "a/b/c" string(1) "c"
*/
The fundamental approach seems OK, but there’s a few things I’d tidy up, including better variable names and scope, and using a more appropriate loop.
Also, from what I can see, you want to find the longest section of the URL path to act as the controller, so probably want to start long and get shorter rather than starting short and getting longer.
EDIT (after accepted) As per hakra’s comment below, the files to be included would presumably always have the extension “.php”, so sample now reflects this.