2012-03-03 92 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