我正在使用cakepp(2.4.7)进行开发,我想知道哪里是编写检查函数以在视图中显示不同内容(按钮、标签等)的最佳位置(控制器、模型等)。
例如,检查用户是否已经喜欢某个帖子(显示"不喜欢"而非"喜欢"),或者检查用户是否是朋友,并显示"删除朋友"而不是"添加朋友"按钮。
我知道这个问题很基本,但我不知道该把代码放在哪里。
我所拥有的: 查看
$hasLiked = $this->requestAction('/userlikes/hasliked/' . $postId); // returns true/ false
if ($hasLiked) {
$this->Html->link('Dislike', array('controller' => 'userlikes', 'action' => 'dislike', $postId));
} else {
$this->Html->link('Like', array('controller' => 'userlikes', 'action' => 'like', $postId));
}
用户类控制器
public function hasliked($postId) {
if (empty($this->request->params['requested'])) {
throw new ForbiddenException();
}
return $this->Userlikes->hasliked($postId, $this->Auth->user('id'));
}
类用户模型
public function hasliked($postId, $userId) {
$result = $this->find('count', array('conditions' => array('post_id' => $postId, 'user_id' => $userId)));
if ($result == 0) {
return false;
} else {
return true;
}
}
但我认为我的解决方案非常肮脏,有更好的方法吗?非常感谢。
我建议更改您的解决方案
类用户模型
public function hasliked($postId, $userId) {
return !empty($this->find('count', array('conditions' => array('post_id' => $postId, 'user_id' => $userId))));
}
用户类控制器
public function hasliked($postId) {
if (empty($this->request->params['requested'])) {
throw new ForbiddenException();
}
$this->set('hasliked',$this->User->hasliked($postId,$this->Auth->user('id')));
}
在您的视图中
<?php if($hasliked) :?>
<?php echo $this->Html->link('Dislike', array('controller' => 'userlikes', 'action' => 'dislike', $postId)); ?>
<?php else: ?>
<?php echo $this->Html->link('Like', array('controller' => 'userlikes', 'action' => 'like', $postId));; ?>
<?php endif;?>
我想你错过了一件事。。。像Like、August、points等特性都是由Ajax完成的。所以,让您的所有操作变得简单,并通过Ajax调用它们。类似-
public function like(){
$this->autoRender = false; // If you wants to use this function just for ajax
if($this->request->is('ajax')){
// do something
// capture all values send by Ajax and Call save function
}else{
return; // if not a ajax call, return
}
}
这只是一个例子----------还有一件事,若你们有东西可以在View上共享,最好创建element
。