0

我正在使用 Doctrine 并尝试在用户浏览器上显示的一组笔记上实现无限滚动。

该应用程序是非常动态的,因此当用户提交一个新笔记时,除了被发送(和存储)到服务器之外,该笔记被直接添加到集合的顶部。

这就是为什么我不能使用传统的分页方法,您只需将页码发送到服务器,服务器就会从中计算出偏移量和结果数。

举个例子来说明我的意思,假设显示了 20 个注释,然后用户添加了 2 个注释,因此显示了 22 个注释。如果我只是请求“第 2 页”,则该页面的前 2 项将是当前显示给用户的页面的最后两项。

这就是为什么我追求一种更复杂的方法,这就是我要解释的方法。

请考虑以下代码,它是服务于 AJAX 请求的服务器代码的一部分以获取更多注释:

// $lastNoteDisplayedId is coming from the AJAX request
$lastNoteDisplayed = $repository->findBy($lastNoteDisplayedId);

$allNotes = $repository->findBy($filter, array('numberOfVotes' => 'desc'));

$offset = getLastNoteDisplayedOffset($allNotes, $lastNoteDisplayedId);

// retrieve the page to send back so that it can be appended to the listing
$notesPerPage = 30       
$notes = $repository->findBy(
  array(), 
  array('numberOfVotes' => 'desc'), 
  $notesPerPage, 
  $offset
);
$response = json_encode($notes);
return $response;

基本上我需要编写方法getLastNoteDisplayedOffset,给定整套注释和一个特定的注释,它可以给我它的偏移量,这样我就可以将它用于上一个 Doctrine 语句的分页。

我知道可能的实现是:

getLastNoteDisplayedOffset($allNotes, $lastNoteDisplayedId) {
    $i = 0;
    foreach ($allNotes as $note) {
        if ($note->getId() === $lastNoteDisplayedId->getId()) {
                break;
        }
        $i++;   
    }
    return $i;
}

我不想遍历所有笔记,因为性能是一个重要因素。我想知道 Doctrine 本身是否有方法,或者您是否可以提出不同的方法。

4

2 回答 2

1

我没有使用过 Doctrine,但解决方案将涉及不使用偏移量而是使用 WHERE 条件。我猜它会是这样的,但我不知道 Doctrine 的语法:

$notes = $repository->findBy(
  array('id < ' => $lastNoteDisplayedId), // I'm guessing the first param is the where condition, don't know the syntax
  array('createdAt' => 'desc'), 
  $notesPerPage
  // remove the offset
);
于 2012-06-11T10:36:31.057 回答
1

在一个旧项目中,我曾经按照您的意愿创建一个无限滚动。

我所做的是一个web服务,它可以接收一个叫做offset的参数。

在我的 javascript 中,我添加了一个事件来检测用户是否向下滚动了足够多的文档。当事件被触发时,我创建了 ajax 查询,我计算了页面中已经存在的元素的数量(它们在一个表中)。

$(window).scroll(function(){
            if  ($(window).scrollTop() + $(window).height() >= $(document).height() - 50){
                lastEvents();
            }
        });


var isLoading = false;
function lastEvents() {
    if (!isLoading) {
      isLoading = true;
      var nb = $('table#events tr').length

      $.ajax({
        url: 'getEvents.php',
        data: {
          offset: nb
        },
        success: function (data) {
          isLoading = false;
          $('.table#events').append(data);
        }
      });
    }
}

然后在我的学说查询中,我做了类似的事情:

$events = Doctrine_Query::create()
            ->select()
            ->from('Events e')
            ->orderBy('e.created_at ASC')
            ->limit(10)
            ->offset($_REQUEST['offset'])
            ->execute();

然后在我的模板中,我生成将附加 JS 的新表格行。

注意:现在,我当然会返回 json 然后在客户端解析它;)

于 2012-06-11T11:13:15.710 回答