Ever since I switched from Coldfusion to PHP, I have not been able to create an Adjacency Model (parent => child menu). I use a method that works well for me, but I am convinced that this can be done way better. This is the situation:
Database(table)
CREATE TABLE IF NOT EXISTS `site_navigation` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`parent_id` tinyint(4) DEFAULT NULL,
`label` varchar(64) NOT NULL,
`item_class` varchar(24) NOT NULL DEFAULT 'nav-item',
`link_class` varchar(48) NOT NULL DEFAULT 'nav-link',
`url` varchar(64) NOT NULL,
`sequence` tinyint(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Database(data)
(1, NULL, 'Home', 'nav-item', 'nav-link', '/nl/', 1),
(2, NULL, 'Categorieën', 'nav-item dropdown', 'nav-link dropdown-toggle', 'javascript:void(0)', 2),
(3, NULL, 'Over', 'nav-item', 'nav-link', '/nl/over', 3),
(4, NULL, 'Contact', 'nav-item', 'nav-link', '/nl/contact', 4),
(5, 2, 'Antiek', 'nav-item', 'dropdown-item', '/nl/antiek', 1),
(6, 2, 'Boeken', 'nav-item', 'dropdown-item', '/nl/boeken', 2),
(7, 2, 'Kunst', 'nav-item', 'dropdown-item', '/nl/kunst', 3),
(8, 2, 'Curiosa', 'nav-item', 'dropdown-item', '/nl/curiosa', 4);
Base on this database example, to build the menu, I use two functions in my Model class The first for the parent layer:
public function main_items()
{
$sql = "SELECT `id`
, `label`
, `title`
, `item_class`
, `link_class`
, `url`
FROM `site_navigation`
WHERE `parent_id` IS NULL";
$stmt = $this->pdo->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$subs = $this->sub_items(); //submenu
$return = '';
foreach ($results as $main) {
$return .= '<li class="'.$main['item_class'].'">';
$return .= '<a class="'.$main['link_class'].'" title="'.$main['title'].'" href="'.$main['url'].'">'.$main['label'].'</a>';
if ($main['id'] == 2) {
$return .= '<div class="dropdown-menu">';
$return .= $subs;
$return .= '</div>';
}
$return .= '</li>';
}
return $return;
}
And the second one to build the submenu for parent (id=2) which I call in the first function:
public function sub_items()
{
$sql = "SELECT `label`
, `title`
, `item_class`
, `link_class`
, `url`
, `page_id`
FROM `site_navigation`
WHERE `parent_id` = 2";
$stmt = $this->pdo->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$return = '';
foreach ($results as $sub) {
$return .= '<a class="'.$sub['link_class'].'" title="'.$sub['title'].'" href="'.$sub['url'].'">'.$sub['label'].'</a>';
}
return $return;
}
And this is the part where Iâm confused about.In the above example there is only one parent / child relationship, but what if there are 3 or even more? Then I would have a proportional number of functions, and that can not and must not be the intention. Can someone please give me a push in the right direction based on the above. I really appreciate every help
Thanks in advance