2012-03-03 95 views
0

我是Symfony的新手,并且正在1.4上开发应用程序。我可以根据我正在处理的一些逻辑使用一些输入,并希望这里的某个人能够指出我正确的方向。Symfony 1.4动态模板

目前,我正在研究一个简单的搜索模块(不是用于jobeet或使用zend搜索的模块),该模块用一些用户放入的文本查询多个表格。用户输入的文本可以在一个更多的三个表格:物品,任务,NPC。所有找到的结果将显示在搜索模块的搜索操作中。

我想要的是,结果显示在搜索行动上作为链接到适当的模块(Item,Quests,Npc分别),但只有在找到该类型的结果。示例(任务和项目的匹配被发现,但不是NPC):

Your search found 1 Item: 
Item 1 

Your search found 1 quest: 
Quest 1 

由于没有发现的NPC,没有必要甚至告诉没有发现任何用户,所以它被省略。这是我遇到麻烦的地方。我不确定如何去做这件事。我只需要在searchSuccess.php中删除和使用if语句,并且只在数组的count()大于1的情况下才显示,但这样做会破坏mvc的目的,对吧?这是实现这一目标的唯一合乎逻辑的解决方案,还是有另一种方法我没有看到?

我真的很感激任何和所有的反馈意见。

回答

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; ?> 
+0

感谢您的帮助,那正是我所需要的。我对mvc比较陌生,不确定是否会在searchSuccess模板中实际使用那么多代码是有帮助的或不利的。我不会在未来犹豫如何。 – Eric 2012-03-03 07:16:54