Using Cake to Build Site Maps
Making site map lists of your server directories can be a chore, especially if your web site has lots of nested folders. Thanks to Cake’s File and Folder utility classes, this can take a lot of the headache out of building dynamic site maps or creating site map files for Google and other search engines.
In the Controller
I’ve created a Files controller in which I’ll do the site mapping:
1
2
3
4
5
6 <?
class FilesController extends AppController {
$name = 'Files';
$uses = null;
}
?>
Next, create an action to run the site mapping loop. I’ve called mine
1 | index() |
. Then instantiate the folder which you’d like to map.
1
2
3
4
5
6 1 function index() {
2 App::import('Core','Folder');
3 $path = ROOT.'scan_this/';
4 $folder = new Folder($path);
5 $this->set('contents',$folder->read());
6 }
On line 2, you can see that I’ve run
1 | App::import() |
to bring the Folder utility class into the controller. Then on line 5, I’ve set the view variable
1 | $contents |
to the results of the Folder utility’s
1 | read() |
function. With
1 | Folder::read() |
, you essentially get an array of folders and files, like the
1 | ls |
Unix command.
In the View
Now in the
1 | app/views/files/index.ctp |
file, I can see the folder’s contents by displaying the contents of the
1 | $contents |
array:
1 <? debug($contents);?>
1
2
3
4
5
6
7
8
9
10
11
12
13 //contents of $contents
Array (
[0] => Array (
[0] => folder_1
[1] => folder_2
[2] => images
)
[1] => Array (
[0] => a file.html
[1] => another_file.html
[2] => index.html
)
)
Now, just cycle through this array, adding your own base URL, and your site map list is ready for the search engines. Of course, you may want to do this with XML if the web site is much more dynamic. For a tutorial on how to use Cake to dynamically create other file formats, check out my book, Beginning CakePHP: From Novice to Professional, Chapter 10: “Routes.” (The section, “Parsing Files with Extensions Other Than .php” explains how to use the RequestHandler component to have Cake map other extensions to Cake controllers and actions.)

