Skip to content

Instantly share code, notes, and snippets.

@clouddueling
Last active December 14, 2015 03:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clouddueling/5021134 to your computer and use it in GitHub Desktop.
Save clouddueling/5021134 to your computer and use it in GitHub Desktop.
Long pulling with Laravel
<?php
class Feed_Controller extends Base_Controller
{
public $layout = 'layouts.feed';
public function get_index()
{
$records = Record::where_deleted(0)
->order_by('updated_at', 'desc')
->take(50)
->get();
$data = array(
'records' => $records
);
$this->layout->nest('content', 'feed.index', $data);
}
public function post_pull()
{
if (Auth::guest())
exit;
$account = Auth::user()->account();
$max_attempts = 150;
$attempts = 0;
$updated_at = Input::has('updated_at') ? Input::get('updated_at') : 0;
while (1) {
$current_record = Record::where_account_user_id($account->id)
->order_by('updated_at', 'desc')
->first();
if (strtotime($current_record->updated_at) > strtotime($updated_at))
break;
Log::pull($current_record->id);
++$attempts;
if ($attempts >= $max_attempts)
exit;
sleep(3);
}
$data['page'] = "";
$records = Record::where_account_user_id($account->id)
->order_by('updated_at', 'desc')
->take(50)
->get();
foreach ($records as $record) {
if (! isset($data['updated_at']))
$data['updated_at'] = $record->updated_at;
// your $data goes here.
}
return json_encode($data);
}
}
@section('title')
Feed
@endsection
@section('content')
<div class='row-fluid mtl'>
<div class='span12 feed'>
</div>
</div>
@endsection
@section('scripts')
<script>
(function() {
var updated_at = 0;
function waitForMsg() {
$.post('/feed/pull', { updated_at: updated_at }, function(data){
var json = jQuery.parseJSON(data);
$('.feed').prepend(json.page);
$('.feed .widget').slideDown('fast');
updated_at = json.updated_at;
setTimeout(function(){
waitForMsg()
}, 1000);
});
}
waitForMsg();
})();
</script>
@endsection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment