2013-06-02 18 views
0

至此,我試圖收緊代碼並停止重複自己。這是一個不斷的鬥爭,哈哈剔除需要檢查控制器中的用戶

在我的看法和我的控制器我檢查,看看用戶是否登錄。這很好,但我只想檢查,看看用戶是否在查看並顯示正確的內容。

最初,在我的控制器中,我看到用戶是否在那裏,然後如果是我用不同的可變參數加載相同的視圖。這似乎有點重複。

public function recentStories(){ 
//This pulls back all the recent stories 
    if (empty($this->user)) { 
     $this->load->view('header_view', array(
     'title' => 'Recent Stories', 
     )); 
     $this->load->view('storyList_view', array(
     'query' => $this->data_model->pullAllStories(), 
    )); 
     $this->load->view('footer_view'); 
    }else{ 
     $this->load->view('header_view',array(
      'user' => $this->users_model->getUser($this->user->user_id), 
      'title' => 'Recent Stories', 
     )); 
     $this->load->view('storyList_view', array(
      'query' => $this->data_model->pullAllStories(), 
      'admin' => $this->admin_model->pulladminRecent(), 
      'user' => $this->users_model->getUser($this->user->user_id), 
     )); 
     $this->load->view('footer_view'); 
    } 
} 

很簡單,我想把這個塊縮小到這樣的東西。

public function recentStories(){ 
//This pulls back all the recent stories 
    $this->load->view('header_view',array(
     'title' => 'Recent Stories', 
    )); 
     $this->load->view('storyList_view', array(
      'query' => $this->data_model->pullAllStories(), 
      'admin' => $this->admin_model->pulladminRecent(), 
      'user' => $this->users_model->getUser($this->user->user_id), 
     )); 
     $this->load->view('footer_view'); 
} 

但是當我做減少代碼,並拿出來檢查,我又回到一個錯誤說,我試圖讓一個非對象的屬性,用戶的部分。顯然,這是在談論用戶。

要嘗試解決這個問題我曾經嘗試都

<?if(isset($user)){ 
    user header code in here 
}else{ 
    non-user header code in here 
}?> 

<?if(!empty($user)){ 
    user header code in here 
}else{ 
    non-user header code in here 
}?> 

兩人都返回「試圖獲得非對象的財產」任何想法將非常歡迎。我真的不喜歡有多餘的代碼。

回答

1
public function recentStories(){ 
    // default values 
    $header_data = array('title' => 'Recent Stories'); 
    $storyList_data = array('query' => $this->data_model->pullAllStories()); 

    // extended data for logged user 
    if (!empty($this->user)) { 
     $header_data['user'] = $this->users_model->getUser($this->user->user_id); 
     $storyList_data['admin'] = $this->admin_model->pulladminRecent(); 
     $storyList_data['user'] = $this->users_model->getUser($this->user->user_id); 
    } 

    // load your views 
    $this->load->view('header_view', $header_data); 
    $this->load->view('storyList_view', $storyList_data); 
    $this->load->view('footer_view'); 
} 

然後在視圖中選中 「如果(isset($用戶)){」 等

+0

非常感謝您!有幾個tweeks這完美的工作! :) – zazvorniki

相關問題