到目前为止,我正在努力收紧我的代码并停止重复自己。这是一场持续的斗争,哈哈
在我的视图和我的控制器中,我正在检查用户是否已登录。这很好,但我只想检查用户是否在视图中,然后显示正确的内容
最初,在我的控制器中,我看到用户是否在那里然后如果是我用不同的可变加载相同的视图。这似乎有点重复。
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');
}
}
Ultimitly,我想把这个块减少到类似的东西。
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
}?>
两人都回来了“试图获得非对象的财产”任何想法都会受到欢迎。我真的不喜欢有多余的代码。
答案 0 :(得分: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');
}
然后在你的视图中检查“if(isset($ user)){”etc。