php - CakePHP: Create a view count -
i have 2 tables:
table 1:
tbl_posts -id -name table 2:
tbl_users -id -name now want count how many users have seen post , keep cache count.
i create table that: (not sure if proper name associations)
tbl_posts_users -id -user_id -post_id now questions: what's proper way associate tables? mean, when user visit post, insert in tbl_posts_users (without repeated registers), , also, having 2 counts: 1 in tbl_users, counting how many posts user saw 1 in tbl_posts, counting how many users have saw post.
in documentation, didn't understand method should use, if should define belongsto or hasmany.
use meaningful table names
based on requirements can name table logs views example "post_views" (i.e. viewing of post user):
tbl_post_views -id -user_id -post_id if tbl_ isn't prefix - remove conventional.
therefore there model named postview belonging both post , user:
class postview extends appmodel { public $belongsto = array('post', 'user'); } don't use view action track view
most current intention implement this:
class postscontroller extends appcontroller { public $uses = array('post', 'postview'); public function view($id) { $this->postview->save(array('user_id' => $this->auth->user('id'), 'post_id' => $id)); $data = $this->post->findbyid($id); $this->set(compact('data')); } } it's better idea not that. recording view in controller code has 2 significant-ish problems:
- it's recording generating view, not user seeing (not same thing)
- it interferes caching (either in php or user's browser)
use image beacon
instead of recording view when request made, include "image beacon" in rendered output:
// end of file view/posts/view.ctp echo $this->html->image(array('action' => 'viewed', $postid), array('class' => 'beacon')); and in posts controller - record post has been viewed, , output valid image (otherwise there error reported user's browser) appropriate headers never cache response:
class postscontroller extends appcontroller { ... public function viewed($id) { $this->postview->save(array('user_id' => $this->auth->user('id'), 'post_id' => $id)); $this->response->disablecache(); $this->response->file('webroot/img/1px.gif'); // 1px gif return $this->response; } } in way, irrespective of how user gets read content, there record user viewed relevant page.
Comments
Post a Comment