简体   繁体   English

有没有更好的方法来执行此PHP代码?

[英]Is there a better way to do this PHP code?

My PHP site has header,body,footer files that are included into the INDEX.PHP page. 我的PHP网站的INDEX.PHP页面中包含页眉,正文,页脚文件。
On the header.php file I have a menu like this 在header.php文件中,我有一个像这样的菜单

    <div id="bottomrow"> 
      <div class="pad"> 
        <ul class="menu left">
          <li class="first <?=$current_home?>"><a href="/"><em>Home</em></a></li>
          <li class="users drop <?=$current_users?>"><a href=""><em>Users</em></a><span class="drop">&nbsp;</span> 
            <ul id="moreheader">
                <li></li>
                <li></li>

            </ul>
          </li>
          <li class="<?=$current_forum?>"><a href=""><em>Forums</em></a></li>
          <li class="drop <?=$current_more?>"><a href="/moreheader"><em>More</em></a><span class="drop">&nbsp;</span> 
            <ul id="moreheader">
              <li><a href=""><em>Widgets</em></a></li>
              <li><a href=""><em>News</em></a></li>
              <li><a href=""><em>Promote</em></a></li>
              <li><a href=""><em>Development</em></a></li>
              <li><a href=""><em>Bookmarks</em></a></li>
              <li><a href=""><em>About</em></a></li>
            </ul>
          </li>
          <li class="moneytabmenu <?=$current_money?>"><a href="/moneytabmenu"><em>Money:<span class="moneytabmenu-total">$0.00</span></em></a></li>
        </ul>
        <ul class="menu right">
          <li class="drop myaccount <?=$current_myaccount?>"><a href="" class="first"><img class="avatar" src="http://gravatar.com/avatar.php?gravatar_id=7ab1baf18a91ab4055923c5fd01d68a2&amp;rating=pg&amp;size=80&amp;default=" height="19" width="19" alt="you" /><em>My 
            Account</em></a><span class="drop">&nbsp;</span> 
            <ul id="myaccount">
              <li><a href=""><em>Dashboard</em></a></li>
              <li><a href=""><em>Account Settings</em></a></li>
              <li><a href=""><em>Settings</em></a></li>
            </ul>
          </li>
          <li class="drop"><a href=""><em>Mail</em></a><span class="drop">&nbsp;</span> 
            <ul id="mailboxheader">
              <li><a href=""><em>InBox</em></a></li>
              <li><a href=""><em>SentBox</em></a></li>
              <li><a href=""><em>Trash</em></a></li>
              <li><a href=""><em>Post Bulletin</em></a></li>
              <li><a href=""><em>View Bulletins</em></a></li>
            </ul>
          </li>
          <li class="drop <?=$current_more?>"><a href=""><em>More</em></a><span class="drop">&nbsp;</span> 
            <ul id="moreheader">
              <li><a href=""><em>Widgets</em></a></li>
              <li><a href=""><em>News</em></a></li>
              <li><a href=""><em>Promote</em></a></li>
              <li><a href=""><em>Development</em></a></li>
              <li><a href=""><em>Bookmarks</em></a></li>
              <li><a href=""><em>About</em></a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
    <!-- END div#bottomrow -->
  </div> 

The menu is similar to above, the above menu is not completed but you can see how it is set up, there are 菜单与上面的相似,上面的菜单还没有完成,但是您可以看到它的设置方式,有

  • list items that make up a menu and SOME of the list items have SUB-LIST items to make up sub-menus on some of the main menu items. 组成菜单的列表项,某些列表项具有SUB-LIST项目,以构成某些主菜单项的子菜单。

    If a user is on any of the pages in a sub-menu, it should add the "current" css class to the parent menu item. 如果用户在子菜单的任何页面上,则应将“当前” css类添加到父菜单项。

    Below is my index.php page where I can determine which page I am on using $_GET for the variable index.php?p=PAGE-NAME 以下是我的index.php页面,可以在其中确定使用$ _GET作为变量index.php的页面是哪个页面?p = PAGE-NAME

    I posted a question earliar similar to this but it was before I did the code below and it didnt get much response, the response it did get all mentioned using arrays but that was beofre they new that I had sub-menus. 我在早期发布了一个与此类似的问题,但是那是在我做下面的代码之前,并没有得到太多的响应,它的响应的确使用了数组,但所有这些都是我新的子菜单。

    So does anyone see a better way to add the css class "current" to a list item above based on which page I am on? 那么,有没有人看到一种更好的方法,根据我所在的页面,将CSS类“ current”添加到上面的列表项中?


    Code on INDEX.php page that processes which menu item should be highlighted INDEX.php页面上的代码,用于处理应突出显示哪个菜单项

     //set variables for menu item to appear as being SELECTED $p = $_GET['p']; $current_home = ''; $current_users = ''; $current_forum = ''; $current_more = ''; $current_money = ''; $current_myaccount = ''; $current_mail = ''; //if home then highlight home menu if($p === 'home'){ $current_home = 'current'; } if($p === 'users.online' || $p === 'users.location' || $p === 'users.featured' || $p === 'users.new' || $p === 'users.browse' || $p === 'users.search' $p === 'users.staff'){ $current_users = 'current'; } if($p === 'forum'){ $current_forum = 'current'; } if($p === 'widgets' || $p === 'news' || $p === 'promote' || $p === 'development' || $p === 'bookmarks' || $p === 'about'){ $current_more = 'current'; } if($p === '=account.money' || $p === 'account.store' || $p === 'account.lottery' || $p === 'users.top.money'){ $current_money = 'current'; } if($p === 'account'){ $current_myaccount = 'current'; } if($p === 'mail.inbox' || $p === '=mail.sentbox' || $p === 'mail.trash' || $p === 'bulletins.post' || $p === 'bulletins.my' || $p === 'bulletins'){ $current_mail = 'current'; } 
  • I would recommend making the whole thing more data driven. 我建议使整个事情更多地由数据驱动。 Create a multi-dimensional array of your menu options and then iterate through the array, outputting the correct HTML. 创建菜单选项的多维数组,然后遍历该数组,输出正确的HTML。

    Here's how I would do it (this hasn't been tested, but the idea is what I'm trying to convey): 这是我的操作方式(尚未经过测试,但是我想传达的是这种想法):

    <?
        $p = $_GET['p'];
    
        $navArray = array();
        $navArray['home'] = array('main' => array('id'=>'home', 'url'=>'/', 'title'=>'Home'));
        $navArray['more'] = array('main' => array('id'=>'more', 'url'=>null, 'title'=>'More'), 
                                  'pages'=> array(
                                    array('id'=>'widgets', 'url'=>'/more-widgets.php', 'title'=>'Widgets'),
                                    array('id'=>'news', 'url'=>'/news.php', 'title'=>'News')));
    
    ?>
    
    
    <div id="bottomrow"> 
          <div class="pad"> 
            <ul class="menu left">
    
                <? foreach($navArray as $navHeading) : ?>
                    <? $current = $navHeading['main']['id'] == $p ? 'current' : ''; ?>
                    <li class="first <?=$current?>"><a href="<?=$navHeading['main']['url']?>"><em><?=$navHeading['main']['title']?></em></a></li>
    
                    <? if (!empty($navHeading['pages'])) : ?>
                        <ul id="sub-<?=$navHeading['main']['id']?>">
                        <? foreach($navHeading['pages'] as $navPage) : ?>
                            <? $current = $navPage['id'] == $p ? 'current' : ''; ?>
                            <li class="<?=$current?>"><a href="<?=$navPage['url'];?>"><em><?=$navPage['title']?></em></a></li>
                        <? endforeach; ?>
                        </ul>
                    <? endif; ?>
                <? endforeach; ?>
            </ul>
        </div>
    </div>
    

    Your HTML can't be simplified much further, but the PHP can probably be done better. 您的HTML不能进一步简化,但是PHP可以做得更好。 It's generally a bad idea to use global variables, but you could probably do something like this instead: 使用全局变量通常不是一个好主意,但是您可以改为执行以下操作:

    function current_tab($page) {
        global $p;
        // Check if $page is a prefix for $p
        if ($page == substr($p, 0, strlen($page))) {
            return "current";
        }
    }
    

    Then in your HTML, use this: 然后在您的HTML中使用:

    <?=current_tab('account');?>
    

    For the non-conforming page names, you're going to need to use special conditions, or you could change the naming convention. 对于不符合标准的页面名称,您将需要使用特殊条件,或者可以更改命名约定。

    First, I would suggest creating a menu class to handle the creation of this menu and call the class method in your index.php. 首先,我建议创建一个菜单类来处理此菜单的创建,并在index.php中调用class方法。 This would separate the code from the presentation, provide abstraction, etc. When you call it you could pass it the page, and the class takes care of the implementation and passes the complete menu back. 这将使代码与表示分离,提供抽象等。当您调用它时,可以将其传递给页面,而类负责实现并向后传递完整的菜单。

    Second, I would suggest using a switch statement instead of if...else with lots of or conditions. 其次,我建议使用switch语句,而不要使用if ... else,否则会带有很多或条件。 You can cascade cases by not including the break keyword: 您可以通过不包含break关键字来级联案例:

    switch( $page) {
      case: 'home':
        $current_home = 'current';
        break;
      case: 'users.online':
      case: 'users.location':
      case: 'users.featured':
      .......
        $current_users = 'current';
        break;
    }
    

    As far as your PHP use goes, you're not using much. 就您对PHP的使用而言,您并没有使用太多。 As I said with your if statements, I think a switch would do much better, the $page would be evaluated once and matched once, unlike each if. 正如我对您的if语句所说的那样,我认为切换会做的更好,$ page将被评估一次并匹配一次,这与每个if不同。 If you could use an loop for the menu, it could cut down on the amount of actual literal HTML in your code. 如果您可以为菜单使用循环,则可以减少代码中实际文字HTML的数量。 If you created arrays to hold each main menu piece (maybe what the others meant), then you could loop over the array and combine the array content, some html, and your variables to create the menu system. 如果创建数组来保存每个主菜单项(也许是其他菜单项的含义),则可以遍历数组并将数组内容,一些html和变量组合起来以创建菜单系统。 Less literal HTML and more efficient use of the PHP. 更少的文字HTML和更有效的PHP使用。

    There's a whole lot you can improve here (maintainability and extensibility are pretty low), but I'd start off with eliminating a few of those conditionals... for example, in the first one, you can check whether the string starts with 'users', which will take care of all the specific cases of 'user'. 您可以在这里进行很多改进(可维护性和可扩展性很低),但是我首先要消除其中一些条件……例如,在第一个条件中,您可以检查字符串是否以'用户”,它将处理“用户”的所有特定情况。

    if(strpos($p, 'users') !== false) { ... }
    

    Same holds for a few of the other cases. 其他一些情况也是如此。

    Anyhow, I suggest you take a look at your server-side script structure. 无论如何,我建议您看一下服务器端脚本结构。 Usually, you can find a more generic solution for this stuff. 通常,您可以找到针对此问题的更通用的解决方案。

    I would suggest having a look at a MVC framework like CodeIgniter (although there are many in the PHP space, CI is my choice). 我建议您看一下像CodeIgniter这样的MVC框架(尽管PHP空间中有很多,但CI是我的选择)。

    You are on the path to writing your own from the ground-up ... with a framework like CI you can re-use nearly all of your existing logic, and just structure it a little different gaining clean separation of concerns and solid templating. 您正在从头开始编写自己的代码……通过像CI这样的框架,您可以重用几乎所有现有的逻辑,并对其结构进行一些改动,从而将关注点和模板完全分离。

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM