The CakePHP Folder
utility has the option to sort the result;
http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::find
App::uses('Folder', 'Utility');
App::uses('Folder', 'Utility');
$myFolder = new Folder('/path/to/directory');
$files = $myFolder->find('*.ctp', true);
foreach ($files as $filename) {
// your code here
}
However, If you do not want to show the pages alphabetically, either prefix the file names with a number and create a special route or don't use the filename for sorting but manually specify the order.
In the end, the only reason for dynamically creating the menu based on the View files is to automatically have the menu generated for you. However, chances are that these changes won't occur often and based on your comment (prefered order) you do have a specific order in mind.
The best solution is to just manually specify the sort order. This will also improve performance as the server will not have to do a directory-scan for each request
For example:
/**
* MenuItems
*
* preferable pass this as a viewVar to the View
*
* file => title
*/
$menuItems = array(
'home' => 'HOME',
'blog' => 'BLOG',
....
);
foreach($menuItems as $file => $title) {
// your code here
}
moving this to a Model
Retrieving the file list inside your View is not the location where this should be done. It's best to read the files beforehand and pass them to the View via a viewvar. Because reading the files is actually 'retrieving data', you may want to create a Model for this that is not connected to a database table.
example
app/Model/Menuoption.php
App::uses('Folder', 'Utility');
class Menuoption extends AppModel {
// this model does not use a database table
public $useTable = false;
public function getOptions()
{
// NOTE: or use the 'manually' created menuItems here
$myFolder = new Folder('/path/to/directory');
return $myFolder->find('*.ctp', true);
}
}
Inside your controller; for example in the beforeRender() callback, or inside a regular action;
public function beforeRender()
{
$this->set('files', ClassRegistry::init('Menuoption')->getOptions());
}
inside your view, you can now access the results via the $files
variable;
foreach ($files as $filename) {
// your code here
}