1

here's a custom & database driven unordered list script for PHP5 5.3.10 As you can see, this method is coming from a procedural background.

It's about 1 year old and today, I was thinking to write it again, the data for this script is coming from 1 SQL table only ; triggered by the dao class and multiple public functions.

This code works as expected but looks a bit ugly to me, what do you think and where would you go from here if you were concidering writing it again ?

Basically the script produce this html :

<div class="menuInside" id="menu">
    <div>
        <ul class="">
            <li class="first"><a onclick="this.blur()" id="bienvenue" href="/bienvenue.html"><img width="109" height="19" alt="Bienvenue" src="/images/menu/bienvenue.png"></a></li>
            <li class="text"><a href="/bienvenue.html">Nous sommes heureux de vous accueillir sur notre site Internet.</a></li>
        </ul>
    </div>
    <div>
        <ul class="insidemiddle ulactive">
            <li class="second"><a onclick="this.blur()" id="marques" href="/lingerie-feminine.html"><img width="102" height="23" alt="Marques" src="/images/menu/marques.png"></a></li>
            <li class="elements"><a href="/barbara.html">Barbara</a></li>
            <li class="elements"><a href="/calida.html">Calida</a></li>
            <li class="elements"><a href="/canat.html">Canat</a></li>
            <li class="elements"><a href="/chantelle.html">Chantelle</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elements"><a href="/charmline-lidea.html">Charmline &amp; Lidea</a></li>
            <li class="elements"><a href="/eminence.html">Eminence</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elements"><a href="/empreinte.html">Empreinte</a></li>
            <li class="elementsOne"><a href="/lisanza.html">Lisanza</a></li>
            <li class="elements"><a href="/lise-charmel.html">Lise Charmel</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elements"><a href="/lou.html">Lou</a></li>
            <li class="elementsThree"><a href="/marjolaine.html">Marjolaine</a></li>
            <li class="elements"><a href="/pain-de-sucre.html">Pain de Sucre</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elements"><a href="/rcrescentini.html">R. Crescentini</a></li>
            <li class="elements"><a class="active" href="/save-the-queen.html">Save The Queen</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elements"><a href="/secret-eva.html">Secret d'Eva</a></li>
            <li class="elements"><a href="/trasparenze.html">Trasparenze</a></li>
            <li class="elements"><a href="/triumph.html">Triumph</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elements"><a href="/twin-set.html">Twin Set</a></li>
        </ul>
    </div>
    <div>
        <ul class="insidemiddle">
            <li class="first"><a onclick="this.blur()" id="lingerie" href="/lingerie-feminine.html"><img width="88" height="21" alt="Lingerie" src="/images/menu/lingerie.png"></a></li>
            <li class="elementsOne"><a href="/lingerie-feminine.html">Féminin</a></li>
            <li class="elements"><a href="/lingerie-masculine.html">Masculin</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elementsTwo"><a href="/lingerie-de-nuit.html">Linge de Nuit</a></li>
            <li class="elements"><a href="/articles-balneaires.html">Articles Balnéaires</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elementsNine"><a href="/collants-bas-mi_bas-chaussettes.html">Collants, Bas, Mi-bas, Chaussettes...</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
            <li class="elementsTen"><a href="/laine-et-soie.html">Laine et Soie</a><img width="9" height="9" class="last" alt="" src="/images/menu/menu_item.png"></li>
        </ul>
    </div>
    <div>
        <ul class="">
            <li class="first"><a onclick="this.blur()" id="contact" href="/contact.html"><img width="106" height="19" alt="Contact" src="/images/menu/contact.png"></a></li>
            <li class="text"><a href="/contact.html">Si vous souhaitez nous faire part de vos impressions ou pour tout autre commentaire...<br>
                <br>
                Nos horaires d'ouvertures</a></li>
        </ul>
    </div>
</div>

Would you like to point me into the right direction ?

Here is the script :

<?php
$id=isset($_GET['id'])?$_GET['id']:1;
($id!=1)?$classNav='menuInside':$classNav='menu';
?>

<div id="menu" class="<?=$classNav?>"><?php $cliao=new cliao();
    $ActiveNav_result=$cliao->SubNav(array(" display_block"=>'=1'," id_marque"=>'='.$id),"id_menu",1);
    $ActiveNav_item=$cliao->fetchResult($ActiveNav_result);
    $Nav_result=$cliao->Nav(array(" display_block"=>'=1'),"id_menu");
    while($MainNav_items=$cliao->fetchResult($Nav_result)){$SubNav_result=$cliao->SubNav(array(" display_block"=>"=1"," id_menu"=>'='.$MainNav_items->id_menu),"id_menu",1);
        if($classNav!="menu"){($MainNav_items->Nav_type==1)?$class='insidemiddle':$class='';
            ($ActiveNav_item->id_Nav==$MainNav_items->id_menu)?$class.=' ulactive':$class.='';
            echo '<div><ul class="'. $class .'">'."\n";
        }else{
            ($MainNav_items->Nav_type==1)?$class='ulactive middle':$class='ulactive';
                echo '<div><ul class="'.$class.'">'."\n";
        }
    while($MainSubNav_items=$cliao->fetchResult($SubNav_result)){
        ($MainNav_items->class_block==2)?$firstclass='class="first"': $firstclass='class="second"';
        echo ($MainNav_items->display_block==1)?'<li '.$firstclass.'><a href="'.$MainNav_items->href_link.'" id="'.$MainNav_items->name.'" onclick="this.blur()"><img src="/images/menu/'.$MainNav_items->name.'.png" alt="'.ucfirst($MainNav_items->name).'" width="'.$MainNav_items->image_width.'" height="'.$MainNav_items->image_height.'" /></a></li>'."\n":'';
        }
        $SubNav_result=$cliao->SubNav(array(" display_block"=>"=1"," id_menu"=>'='.$MainNav_items->id_Nav),"id_menu");
    while($MainSubNav_items=$cliao->fetchResult($SubNav_result)){($MainSubNav_items->Nav_last=="yes")?$last='<img src="/images/menu/menu_item.png" alt="" width="9" height="9" class="last" />':$last='';
        ($MainSubNav_items->id_marque==$id)?$activeclass='class="active"':$activeclass='';
?>
        <li class="<?=$MainSubNav_items->Nav_class?>"><a href="<?=$MainSubNav_items->href_link?>" <?=$activeclass?>><?=$MainSubNav_items->text?></a><?=$last?></li><?="\n"?><?php }echo '</ul></div>'."\n";
    }
?>
</div>
jmayeux
  • 31
  • 5
  • 2
    I'm speechless. Not to be mean, but start over. – Paul Dessert Nov 13 '12 at 20:09
  • 2
    It's novice code, but it isn't that frightening. It smacks of a PHP newbie who paid a lot of attention to how he Should Be Doing Things without necessarily understanding why. I think we'd all rather see code like this than dig through WordPress source, and this guy is even interested in fixing his. :) – Winfield Trail Nov 13 '12 at 20:37

1 Answers1

0

I always make sure to tie my database contents into the generated HTML whenever possible. For instance, instead of:

if($classNav!="menu"){($MainNav_items->Nav_type==1)?$class='insidemiddle':$class='';
        ($ActiveNav_item->id_Nav==$MainNav_items->id_menu)?$class.=' ulactive':$class.='';
        echo '<div><ul class="'. $class .'">'."\n";
    }else{
        ($MainNav_items->Nav_type==1)?$class='ulactive middle':$class='ulactive';
            echo '<div><ul class="'.$class.'">'."\n";
    }

I'd store the desired final $ClassNav in the database and write it like this:

echo '<ul class='$ClassNav'>\n';

I would also skip the messy class='first' nonsense and use the CSS first child pseudoelements when possible.

I see you're using while a lot. I don't blame you, that's how 90% of the PHP guides (and example code on PHP.net) do things. However, it's not ideal because:

  1. it relies on the inscrutable and awkward Internal Row Pointer, arguably the least intuitive method for navigating arrays, and
  2. as a result you have to write a lot of ridiculous bloat like $MainSubNav_items=$cliao->fetchResult($SubNav_result).

Make your life easier. Covert the data into an array in the first place, and then either access it with foreach ($data as $record) { $out .= $record['fieldname']; } or for ($i = 0; $i < sizeOf($record); $i++) { $out .= $record[$i]['fieldname']; }.

In that comparison foreach is more concise, whereas for gives you more access to flow control.

Finally, consider rewriting this as a recursive function: one that renders through the list, and when it encounters a submenu, calls itself to generate the next level. Much easier, much more robust. :)

As an example, here's the menu generation code that I use inside my (in-house) object-oriented toolkit:

public function Render($Menu = false){ 
    $Menu = (is_array($Menu) ? $Menu : $this->MainMenu); // If no menu array is passed, pull the main menu object from the class constructor
    $Out = "<ul class='SuuiMenu'>"; //building an $Out string instead of echoing is preferable as the resulting function can be used in more contexts

    foreach ($Menu as $Entry){
        if ($Entry['Link'] !== '#'){ //I use a link value of # for submenu headers
            $Entry['Link'] = base_url().$Entry['Link'];
        }
        $Out .= "
            <li>
                <a href='{$Entry['Link']}'>{$Entry['Title']}</a>";
            if (isset($Entry['Children'])){ //if this menu entry has 'Children' in its array, this method calls itself with that child's array as an argument and adds the whole thing to $Out
                $Out .= $this->Render($Entry['Children'], false);
            }   
        $Out .="</li>
        ";
    }

    $Out .= "</ul>";

    return $Out; //to be echoed, modified further in PHP-DOM, cached, etc :)
}
Winfield Trail
  • 5,535
  • 2
  • 27
  • 43