【问题标题】:Symfony 1.4 Dynamic TemplatesSymfony 1.4 动态模板
【发布时间】:2012-03-03 04:20:33
【问题描述】:

我真的是 Symfony 的新手,并且正在开发一个 1.4 的应用程序。我可以在我正在研究的一些逻辑上使用一些输入,并希望这里有人可以为我指明正确的方向。

目前,我正在开发一个简单的搜索模块(不是用于 jobeet 或使用 zend 搜索的模块),它使用用户输入的一些文本查询多个表。用户输入的文本可以在一个或多个中找到三个表:项目,任务,Npc。所有找到的结果都将显示在搜索模块的搜索操作中。

我想要的是,搜索操作中的结果显示为指向正确模块(分别为项目、任务、Npc)的链接,但前提是找到了该类型的结果。示例(如果找到了任务和物品匹配,但没有找到 NPC):

 Your search found 1 Item:
 Item 1

 Your search found 1 quest:
 Quest 1

由于没有找到 NPC,甚至不需要告诉用户没有,所以省略了。这就是我遇到麻烦的地方。我不太确定如何去做。我可以直接退出并在 searchSuccess.php 中使用 if 语句,并且仅在数组的 count() 大于 1 时显示这些语句,但这违背了 mvc 的目的,对吧?这是实现这一目标的唯一合乎逻辑的解决方案,还是我没有看到其他方法?

非常感谢任何和所有反馈。

【问题讨论】:

    标签: php mysql templates symfony1 module


    【解决方案1】:

    有无数种方法可以做到这一点,最简单的可能是这样的:

    // controller
    public function executeSearch(sfWebRequest $request)
    {
       $this->results = array();
       // well assume you are using sfForm and have validated the search query
       // which is $searchTerm and that each of your tables has a search method
    
       // well also assume youre using object routes for these models
       $this->actionMap = array(
          'Npc' => 'npc_show',
          'Quest' => 'quest_show',
          'Item' => 'item_show'
       );
    
       foreach(array_keys($this->actionMap) as $model)
       {
          $modelResults = Doctrine_Core::getTable($model)->search($searchTerm);
          if($modelResults)
          {
             $this->results[$model] = $modelResults;
          }
       }
    
       return sfView::SUCCESS;  
    }
    

    所以我们看到的是$results 一个多维数组,由查询返回结果的模型的顶级元素组成。没有任何匹配结果的模型被省略。 $actionMap 包含一个 ModelName => Routename 映射数组。

    // in your searchSuccess
    
    <?php if(count($results)): ?>
       <?php foreach($results as $model => $modelResults): ?>
           <?php printf("<h3>Your search found %s %s results:</h3>", $modelResults->count(), $model); ?>
           <ul>
              <?php foreach($modelResults as $result): ?>
                 <li><?php echo link_to($result, $actionMap[$model], $result); ?></li> 
              <?php endforeach; ?>
           </ul> 
       <?php endforeach; ?>
    <?php else: ?>
       <h3>No results found.</h3>
    <?php endif; ?>
    

    【讨论】:

    • 感谢您的帮助,这正是我所需要的。我对 mvc 比较陌生,不确定在 searchSuccess 模板中实际使用那么多代码是否有益或有害。我以后不会那么犹豫了。
    猜你喜欢
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2011-11-09
    • 2011-09-18
    • 2011-04-06
    • 2011-04-21
    • 1970-01-01
    相关资源
    最近更新 更多