2013-11-14 19 views
0

我有點困惑,使用fuelPHP 1.7。FuelPHP基礎知識,使用模型結果查看

控制器

class Controller_Website extends Controller 
{ 
    public function action_index() 
    { 
     // http://fuelphp.com/docs/general/views.html 

     $data = Website::get_results(); 

     //var_dump($data) // (data is found here); 

     $views = array(); 
     $views['head'] = View::forge('common/head', $data); 
     $views['header'] = View::forge('common/header', $data); 
     $views['sidebar'] = View::forge('common/sidebar', $data); 
     $views['content'] = View::forge('common/content', $data); 
     $views['footer'] = View::forge('common/footer', $data); 

     // return the rendered HTML to the Request 
     return View::forge('website', $views)->render(); 
    } 
} 

模型

class Website extends \Model 
{ 
    public static function get_results() 
    { 
     // Database interactions 
     $result = DB::select('menu', 'url', 'title', 'text') 
      ->from('aaa_website') 
      ->where('id', '=', 1035) 
      ->and_where('visible', '1') 
      ->execute(); 

     return $result; 
    } 
} 

所有好SOFAR。數據在控制器中查詢並找到。我試圖做到的是用在我的數據:

(嵌套)查看

<html> 
<head> 
    <?php echo $head; ?> 
</head> 
<body> 
<header> 
    <div class="container"> 
     <?php echo $header; ?> 
    </div> 
</header> 
<div class="row"> 
    <div class="container"> 
     <div class="col-md-4"> 
      <?php echo $sidebar; ?> 
     </div> 
     <div class="col-md-8"> 
      <?php echo $content; ?> 
     </div> 
    </div> 
</div> 
<footer> 
    <div class="container"> 
     <?php echo $footer; ?> 
    </div> 
</footer> 
</body> 
</html> 

頭視圖(嵌套):

<title><?php echo $title; ?></title> 

內容視圖(嵌套):

<h1><?php echo $title; ?></h1> 
<div class="welcome_user"><?php echo $text; ?></div> 

等等。

本示例視圖中的變量不可用,因爲它們未在控制器中明確設置。他們是否必須顯式設置或者傳遞數據對象也是可能的?如果是這樣,我如何以正確的方式訪問這些對象數據? FuelPHP在這裏缺乏很好的例子,現在我被卡住了。

我該怎麼做?

回答

1

視圖數據從索引數組轉換爲視圖變量命名。所以:

View::forge('something', array('param' => 'value')); 

將對應於以下幾種觀點:

<h1><?=$param?></h1> 

如果事情會錯的是你通過簡單的DB結果的看法。你需要從數據庫中獲取結果的第一個結果,就像這樣:

class Website extends \Model 
{ 
    public static function get_results() 
    { 
     // Database interactions 
     $result = DB::select('menu', 'url', 'title', 'text') 
      ->from('aaa_website') 
      ->where('id', '=', 1035) 
      ->and_where('visible', '1') 
      ->as_assoc() 
      ->execute() 
      ->to_array(); 

     return reset($result); 
    } 
} 

請注意,我第一次使用->to_array()結果對象轉換爲數組,然後reset()得到的第一個結果。我還添加了->as_assoc()以確保您獲得數組結果,->as_object()會爲您提供stdClass實例。

+0

謝謝你讓我走! – Klaaz

+0

不客氣,喜歡用FuelPHP :) –