Source

sfPropelORMRatableBehaviorPlugin / README.rst

sfPropel15RatablePlugin

A behaviour for propel 1.5/1.6 and symfony 1.4.x to rate your objects

How to install

  • add this plugin as a submodule

    git submodule add git://github.com/matteosister/sfPropel15RatableBehaviorPlugin.git plugins/sfPropel15RatableBehaviorPlugin

  • enable the plugin in your ProjectConfiguration class

config/ProjectConfiguration.class.php

<?php

require_once dirname(__FILE__) . '/../lib/vendor/symfony/autoload/sfCoreAutoload.class.php';
sfCoreAutoload::register();

class ProjectConfiguration extends sfProjectConfiguration
{
  public function setup()
  {
    // ...
    $this->enablePlugins('sfPropel15RatableBehaviorPlugin');
    // ...
  }
}
  • add the ratable behavior to a class in your schema file

config/schema.xml

<table name="article">
    <behavior name="ratable" />
    <!-- ... -->
</table>
  • rebuild your model
php symfony propel:build-all

Columns And Method generated

The behavior adds two column to the object. The average rating, and the total number of votes. Here is a full parameters specification with default values.

<behavior name="ratable">
    <!-- the db name of the average column -->
    <parameter name="average_column" value="the_average"></parameter>
    <!-- the php name of the average column -->
    <parameter name="average_column_phpname" value="Average"></parameter>
    <!-- the db name of the votes number column -->
    <parameter name="nb_votes_column" value="ratable_nb_votes"></parameter>
    <!-- the php name of the votes number column -->
    <parameter name="nb_votes_column_phpname" value="NbVotes"></parameter>
    <!-- the average precision  -->
    <parameter name="precision" value="1"></parameter>
</behavior>

The precision value is passed to the php round function to store and retrieve average from db

[php function round] http://it.php.net/manual/en/function.round.php

In the base class of your object model you'll find two new methods:

public function getRating($max = 5, $precision = 1) // $max and $precision default values comes from the schema parameters
public function setRating($rating)

see the class comments for reference

How to use

<?php
$article = new Article(); // nb_votes: 0, avg: null

$article->setRating(3); // you need to call the save() method to actually write the data to db.
$article->save() // nb_votes: 1, avg: 3

$article->setRating(4);
$article->save(); // nb_votes: 2, avg: 3.5

$article->getRating(); // 3.5 out of 5
$article->getRating(10); // 7 out of 10
$article->getRating(5, 0); // 4 out of 5