We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Visit counter

Hello,

I have to make unique visit counter for products (So ppl cant refresh the site and rise popularity). Since im working on RESTful api, I need idea how to do it (front is AngularJS and backend is Phalcon). I make a new column for visits number in db, at products table and now need idea for implementation of that system.

Thanks...

Without a registration process, there's not much you can do.

Counting by IP address is the worst possible option, there can be multiple clients from the same IP and IPs can be changed with proxies/VPNs easily.

You could use cookies to tag unique visitors, but that's in the client realm and can be modified/regenerated without your knowledge.

Google Analytics is your best option imo, you can export a visitor list and map producs to their URLs

Since HTTP is a stateless protocol, we're put in a bad position to distinguish visitors. If you add IPv4 issues as well, then such simple task starts to get mission critical - i.e. you need to cover many aspects on your own.

Like @lajosbencz said, w/o forcing users to login you can't do much. GA is your best shot for such reports.



23.6k

Hmmm ... what about simple counter. Not unique? Is that possible? So i need just to update visit counter column per visits of specific product.

edited May '16

Sure:

class ProductController extends \Phalcon\Mvc\Controller
{
    public function viewAction($rowId)
    {
        $product = Product::findFirstById($rowId);
        if(!$product) {
            throw new \Exception('Product not found');
        }
        $product->setVisitCount($product->getVisitCount()+1);
        $product->update();
        $this->view->product = $product;
    }
}


23.6k
edited Jun '16

I have this error in my nginx api log ...

PHP Fatal error:  Call to undefined method Phalcon\\Mvc\\Model\\Resultset\\Simple::setVisitCount() in my products controler

Because you're trying to call Model method on a list of Models (ResultSet).

Note the findFirstById in my example



23.6k
edited Jun '16

Because you're trying to call Model method on a list of Models (ResultSet).

Note the findFirstById in my example

Ahh I see now, ok I did some refactoring since im not using views (rest api on backend) and changed from findFirstById to findFirstBySlug.. I have no errors atm but json is empty ..

{

    "status": "success",
    "http_code": 200,
    "data": [ ]

}

When I use find(), result is working but when I use findFirstBySlug() I have that empty success ..