Thursday, October 23, 2014

article hit count with session using article_model based codeigniter

private function _get_article_data($article) {
        $category = $this->category_model->get($article['category_id']);
        $this->support->set_working_category($category);

        $data = array();
        $data['category'] = $category;
       
        //extend and traffic
        $e_article_key = $this->support->get_article_session_name() . $article['id'];
        $article_extend = $this->session->userdata($e_article_key);
        $db_article_extend = $this->article_extend_model->get(array('article_id' => $article['id']));       
        if (isset($db_article_extend['hitcount']) &&
                isset($article_extend['hitcount']) &&
                $db_article_extend['hitcount'] != $article_extend['hitcount']) {
            //if another process view this article
            $article_extend = $db_article_extend;
        }
        if (!isset($article_extend['hitcount'])) {
            //session not exists
            if (isset($db_article_extend['hitcount'])) {
                //db not set
                $article_extend = $db_article_extend;
            }
            if (empty($article_extend)) {
                //create hitcount in db
                $article_extend = array();
                $article_extend['article_id'] = $article['id'];
                $article_extend['hitcount'] = 0;
            }
            $article_extend['hitcount'] = $article_extend['hitcount'] + 1;

            $this->article_extend_model->save($article_extend);
            $this->session->set_userdata($e_article_key, $article_extend);
        }
        $data['article_extend'] = $article_extend;

        return $data;
    }

No comments: