Zend FR

Consultez la FAQ sur le ZF avant de poster une question

Vous n'êtes pas identifié.

#1 05-12-2007 15:12:39

Mr.MoOx
Administrateur
Lieu: Toulouse
Date d'inscription: 27-03-2007
Messages: 1444
Site web

RatingBar (portage de php old school à zfisation)

Bonjour à tous,

Je poste un peu à l'arrache (par fleim de faire fonctionner mon cerveau) mais je pense que vous m'aiderais sans faire trop chauffer le votre.
J'avais développer une rating Bar (barre de notation à base d'étoiles) en php/css (et js/ajax si js activé) que j'utilisais à la porc de cette manière

Code:

    $rat_id = 'unIdDeBD';
    require "lib/mx.rating_param.php";

Sur cette page, vous trouverez une utilisation de cette rating bar (au milieu de la page en dessous de la vidéo - que vous pouvez regarder d'ailleurs ^^): http://bouillac-city-production.moox.fr/?movie=BN+Wars (regardez l'url des liens sur les étoiles...)
Je vourais la porter en POO avec le zf mais je sais pas trop par où commencer...
Je sais pas si je dois faire un controller, un extension de zend_db_table, un helper ou un combo de tout ça (je pense plutôt un combo mais j'ai un peu la fleime d'y réfléchir je vous avoue).
Un petit coup de pouce me permettrait de vous fournir à tous un super barre de notation hyperparamétrable.

Voici mon ancien code, j'ai laissé les commentaires ça vous aidera à piger un peu.
Par contre j'omets les code CSS et JS car il ne nous interesse pas ici

mx.rating_param.php (fichier de config)

Code:

<?php
/**
 * MoOx's Rating Bar
 * (PHP Part 1/2)
 *
<Description>
    This is a rating bar script done with PHP, MySQL, CSS and Javascript 
    that allows users to rate things (videos, jokes or everythings else...).
    It is unobtrusive, meaning that if Javascript is off it will still work.
    You can set the number of rating units you want to use with a different
    number of visible unit (i.e. with the precision you want)
        e.g.: 5 stars for display, with the possibility to vote with 10 
        differents level.
    This script is very PARAMETRABLE so you should be able to adapt it to your 
    situation without too any trouble.
    See Tags bellow for details and parameters documentation.
</Description>

<Require>
    2 PHP files (mx_rating_param.php, mx_rating.php)
    1 CSS file (mx_rating.css)
    1 image (with the 3 differents states of the star in...)
    2 lines of code in a PHP script to display a rating bar
    <Optional>
        3 Javascript files (prototype.js, behaviour.js, mx_rating.js) for AJAX :)
    </Optional>
</Require>

<Usage>
    In a PHP script, just write this : 
    
        $rat_id = YOUR_ID;
        require "YOUR_PATH/NAME_OF_THIS_FILE";
        
    YOUR_ID must be corresponding with an id of an existing record in your db
    YOUR_PATH can be empty (depending on your web files organisation)
    NAME_OF_THIS_FILE (no comment :)
</Usage>

<Details>
    EN GENERAL, you just choose one way for you rating bar, so just use
    this package like this, after changing the parameters.
    
    /!\
    If you use it with differents ways (differents styles, differents data 
    in your db...), just copy this files with differents names, and modify
    the parameters for each rating bars. 
    
    /!\
    This script could be in a folder you want (for a better organisation).
    Just specify the path (see <Usage> and <Parameters> for details)...
    
    <PHP>
        You just have to verifiy if your PHP version allow you to use global 
        variables like $_GET or $_SERVER. PHP 4 or higher often allow this...
        This script hold you to rate something once. So, to rate this ONCE, 
        it writes a cookie (time length is PARAMETRABLE). And if cookies are 
        disable, it remember the ip used during a moment in the db (it remember 
        a number of ip adress you want).        
    </PHP>
    
    <MySQL>
        This script just need some modifications on a existing table...
            ALTER TABLE tablename
                ADD rating_value INT NOT NULL ,
                ADD rating_votes INT NOT NULL ,
                ADD rating_ips TEXT NOT NULL ;
        Or needs a table with some records....
            CREATE TABLE tablename (
                id INT(11) NOT NULL auto_increment,
                rating_value INT(11),
                rating_votes INT(11),
                rating_ips TEXT,
                PRIMARY KEY  (id)
            );
        You can change the name of the fields when you create it ! 
        Just specify them in the parameters.
    </MySQL>
    
    <CSS>
        This script is using CSS 2.O for a good looking presentation.
        In this file you could change one thing : the url of the used image.
        The image contains the 3 differentes states of a star could take.
        2 to display the rating, and one using when you rate (onmouseover effect)
        You can change it but be carful. You should change the parameters if the
        dimensions are not the same than the original image. 
        See <Parameters> $rat_pixel_size for details.
    </CSS>
    
    <Javascript>
        This script is unobstrusive (i.e. if Javascript is off it will still work)
        For the javascript works fine, you need 3 files (that are include in the package)
            - prototype.js
                a famous javascript framework use for AJAX update
                http://www.prototypejs.org/
            - behaviour.js
                a script to do unobstrusive javascript
                http://bennolan.com/behaviour/
            - mx_rating.js
                my file create for this script using the 2 above
                
        Just include this 3 files in your web page and AJAX will work if it could...
        If you don't include them, it's not a probleme. The script will work...
    </Javascript>
</Details>

<Parameters>
    $rat_path 
     -> relative path from the file you include this...
        The same path when you include it (may be not...).

    //SQL parameters
    $_adr, $_usr, $_pass, $_db
     -> DB connection, set your db id here
    $rat_sql_tab
     -> (table name) table where you have the fields bellow
    $rat_sql_id
     -> (field name) unique id of your table
    $rat_sql_val
     -> (field name) field where are stored the values
    $rat_sql_vot
     -> (field name) field where are stored the number of votes
    $rat_sql_ips
     -> (field name) field where are stored the ips which don't accept cookie

    $rat_unit
     -> Unit for display (default value => 5)
        Corresponding with the number of stars you show
    $rat_precision
     -> Real Unit of the rating (default value => 10)
        Corresponding with the number of differents ratings
    $rat_pixel_size
     -> Pixel size of the image (image must be a square!) (default value => 30)
        "Image must be a square"... It's wrong. Image must contains the equivalent
        of 3 squares. (original image dimensions are 30*90...)
    $rat_cookietime
     -> DUREE DU COOKIE (in seconds) (default value => 60*60*24*30 : 1 month)
    $rat_nbrememberip
     -> Number of Ip remember in the DB (use if no cookies are off...) (default value => 10)

    // Optional Sentence Display settings
    $rat_showWords = true;
     -> Wheter your show complementary words or just the rating bar (if false, forgot the parameters bellow)
        $rat_charset = 'ISO-8859-1';
         -> Encoding of the text (Just use for AJAX...) ('UTF-8', 'ISO-8859-1'...)
        $rat_precision_dec
         -> Precision of decimal (default value => 1)
            Corresponding with the precision when the rating apppears 
        $rat_word_ratethis
         -> Sentence to invite for voting (default => 'Notez cette vidéo :')
        $rat_word_rated
         -> Sentence to say you've already voted (default => 'Vous avez déjà noté cette vidéo')
        $rat_word_rate, $rat_word_with, $rat_word_vote
         -> $rat_word_rate.' '.$rat_format_note.'/'.$rat_unit.' '.$rat_word_with.' '.$rat_votes.' '.$rat_word_vote
            e.g.:   "Note : 2.9/5 avec 5 votes"
                    "Rating : 2.9/5 ( 5 votes cast )"

    // Others parameters
    $rat_showIndexphp
     -> Do you want to display 'index.php' in the url ? ...
        If $_SERVER['HTTP_REFERER'] is empty (e.g.: disables from browser or 
        don't exists because this is the first page load in the browser),
        this script use a $_GET['from'] parameter for comming back to the page
        after doing his job. And some people like me use funky url like 
        "http://www.mywebsite/?location=home". So this people doesn't whant to 
        see after comming back url like this 
        "http://www.mywebsite/index.php?location=home"
        Set this parameter to false to hide "index.php" in the url, true else
        (false is recommanded :)
</Parameters>
 *
 * @name mx.rating_param.php
 * @require mx.rating.php
 *
 * @version 1.0
 * @author MoOx <m@moox.fr> http://mr.moox.fr/
 * @copyright (c) 2006 MoOx
 */

$rat_path = 'php/lib/mx.rating_param.php';

//DB connection, set your db id here
    $_adr = "xxxx";
    $_usr = "xxxx";
    $_pass = "xxxx";
    $_db = "xxxx";
// SQL 
$rat_sql_tab = 'bcp_videos';
$rat_sql_id = 'id';
$rat_sql_val = 'rating_value';
$rat_sql_vot = 'rating_votes';
$rat_sql_ips = 'rating_ips';

//Rating Options
$rat_unit = 5;
$rat_precision = 10;
$rat_pixel_size = 30;
$rat_cookietime = 60*60*24*30;
$rat_nbrememberip = 10;

//Optional Display settings
$rat_showWords = true;
    $rat_charset = 'ISO-8859-1';
    $rat_precision_dec = 1;
    $rat_word_ratethis = 'Notez cette vidéo :';
    $rat_word_rated = 'Merci d\'avoir voté';
    $rat_word_rate = 'Note :';
    $rat_word_with = 'avec ';
    $rat_word_vote = 'vote';

$rat_showIndexphp = false;

require "mx.rating.php"; // Don't change this :)

mx.rating.php (traitement)

Code:

<?php
/**
 * MoOx's Rating Bar
 * (PHP Part 2/2)
 * Don't use the file. You must use <mx_rating_param.php>
 * This script needs a lot a variable define in <mx_rating_param.php>.
 * <mx_rating_param.php> will include this file for you :)
 * See <mx_rating_param.php> for better documentation.
 *
 * @name mx.rating.php
 * @require mx.rating_param.php
 *
 * @version 1.0
 * @author MoOx <m@moox.fr> http://mr.moox.fr/
 * @copyright (c) 2007 MoOx
 */

$rat_db = mysql_connect ($_adr, $_usr, $_pass) or die ("Connexion impossible");
mysql_select_db ($_db) or die ("Base inconnue");

if ($_GET['ratingcode'] != "") {
    $rat_result = explode(":", $_GET['ratingcode']);
    $rat_id = $rat_result[0];
}

$rat_query = mysql_query("
    SELECT ".$rat_sql_val.", ".$rat_sql_vot.", ".$rat_sql_ips." 
    FROM ".$rat_sql_tab." 
    WHERE ".$rat_sql_id." = '".$rat_id."' "
) or die(" Error: ".mysql_error());

$rat_sql = mysql_fetch_array($rat_query);
$rat_value = $rat_sql[$rat_sql_val];
$rat_votes = $rat_sql[$rat_sql_vot];
$rat_ips = ($rat_sql[$rat_sql_ips]!="")?unserialize($rat_sql[$rat_sql_ips]):array();
$rat_ip = $_SERVER['REMOTE_ADDR'];

// determine whether the user has voted or not
if ($_COOKIE['mx_rating_'.$rat_id] == 'voted') {
    $rat_voted = true;
} else {
    $rat_voted = (array_search($rat_ip, $rat_ips)===false)?false:true;
}

if ($_GET['ratingcode'] != "") { // You just want to display the rating bar    
    //update
    if ( !$rat_voted && ($rat_result[2] >= 1 && $rat_result[2] <= $rat_precision) && ($rat_result[1] == $_SERVER['REMOTE_ADDR'])) { 
    // keep votes within range, make sure IP matches - no monkey business!        
        $rat_cookietime+=time();
        setcookie('mx_rating_'.$rat_id, 'voted' , $cookietime, "/");
        if (count($rat_ips) >= $rat_nbrememberip ) {
            array_shift($rat_ips);
        }
        array_push($rat_ips,$rat_ip);

        $result = mysql_query("
            UPDATE ".$rat_sql_tab."
            SET 
                ".$rat_sql_val." = ".$rat_sql_val."+".$rat_result[2].",
                ".$rat_sql_vot." = ".$rat_sql_vot."+1,
                ".$rat_sql_ips." = '".serialize($rat_ips)."'
            WHERE ".$rat_sql_id." = '".$rat_result[0]."'
        ");
    }
    
    // go back to the page we came from if normal use (without AJAX)
    if ($_GET['ajax'] != "ok") {
        if ($_GET['from'] == "")
            header("Location: ".$_SERVER['HTTP_REFERER']);
        else
            header("Location: ".$_GET['from']);
    } else {
        header("Content-type: text/html; charset=".$rat_charset);
        // Update values without query
        $rat_value += $rat_result[2];
        $rat_votes++;
        $rat_voted = true;
    }
}

// Calculate the good note for the precision and units required
$rat_wrong_note = ($rat_votes=="" || $rat_votes==0)?0:$rat_value/$rat_votes;
$rat_format_note = @number_format($rat_wrong_note*$rat_unit/$rat_precision,$rat_precision_dec);

if ($rat_votes>1) {$rat_word_vote .= 's';} //plural form votes/vote
    
    $rat_width_1 = @number_format($rat_format_note*$rat_pixel_size,$rat_precision_dec);
    $rat_width_2 = @number_format(($rat_unit-$rat_format_note)*$rat_pixel_size,$rat_precision_dec);
    $rat_bp = $rat_pixel_size-(@number_format($rat_format_note,$rat_precision_dec)-@number_format($rat_format_note,0))*$rat_pixel_size;
?>
<!-- MoOx's Rating Bar -->
<div id="mx_rating_<?php echo $rat_id; ?>">
    <div><?php echo (!$rat_voted)?$rat_word_ratethis:$rat_word_rated;?></div>
    <div class="mx_rating" style="height: <?php echo $rat_pixel_size; ?>px">
        <div class="mx_rating_draw">
            <div class="draw_1" style="width: <?php echo $rat_width_1; ?>px ; height: <?php echo $rat_pixel_size ?>px;"></div>
            <div class="draw_2" style="width: <?php echo $rat_width_2; ?>px ; height: <?php echo $rat_pixel_size ?>px; background-position: <?php echo $rat_bp; ?>px 0"></div>
        </div>
        <div class="mx_rating_vote">
        <?php
            if (!$rat_voted) {
                for ($rat_i = $rat_precision; $rat_i >= 0; $rat_i--) {
                    $rat_tmp = @number_format($rat_i,$rat_precision_dec);
                    echo '
                    <a href="'.mx_rating_mkLink($rat_id, $rat_tmp, $rat_path).'" class="mx_rating_starforvote" style="width: '.$rat_tmp*$rat_pixel_size/($rat_precision/$rat_unit).'px; height: '.$rat_pixel_size.'px;"></a>
                    ';
                }
            }
        
        ?>
        </div>
    </div>
    <?php
        if ($rat_showWords) {
            echo '<div>'.$rat_word_rate.' '.$rat_format_note.'/'.$rat_unit.' '.$rat_word_with.$rat_votes.' '.$rat_word_vote.'</div>';
        }
    ?>
</div>
<!-- /MoOx's Rating Bar -->
<?php

//Some functions used...
function mx_rating_mkLink($id, $i, $path) {
    global $rat_showIndexphp;
    $url = $path.'?ratingcode='.$id.':'.$_SERVER['REMOTE_ADDR'].':'.$i;
    if ($_SERVER['HTTP_REFERER'] == "") {
        $url .= '&amp;from='.mx_rating_getURLencode($rat_showIndexphp); //&amp; for valid xhtml ;)
    }
    return $url;
}

// Returns current url (encoded for url). Used if $_SERVER['HTTP_REFERER'] is empty...
function mx_rating_getURLencode($showIndexphp = false) {
    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    if ($_SERVER['QUERY_STRING'] != "" )
    $url.= '?'.$_SERVER['QUERY_STRING'];
    if ( !$showIndexphp ) {
        $url = str_replace("/index.php","/",$url);
    }
    return urlencode($url);
}

Au niveau base de données, cette rating bar s'appuie sur 3 champs (nombre de votes, sommes des votes et les 10dernières ip qui ont votés). C'est assez simple.

C'est un peu le bordel là dedans, mais j'espère que vous arriverez malgrés ça à m'éclairer un peu

Hors ligne

 

#2 05-12-2007 18:16:26

2mx
Membre
Lieu: Grenoble
Date d'inscription: 06-08-2007
Messages: 125

Re: RatingBar (portage de php old school à zfisation)

Je vais moi aussi avoir besoin de faire un sytème de notation. Je n'y ai pas encore réfléchi, comme j'utilise Jquery je pense utiliser ce plugin http://www.phpletter.com/Demo/Jquery-St … ng-Plugin/

Comme ça, à froid, je dirais faire une classe My_???_Rating auquel je passe un Db adapter, le nom de la table, le noms des colonnes...
Puis dans une Action d'un controleur instancié My_???_Rating...

Hors ligne

 

#3 05-12-2007 23:05:21

Mr.MoOx
Administrateur
Lieu: Toulouse
Date d'inscription: 27-03-2007
Messages: 1444
Site web

Re: RatingBar (portage de php old school à zfisation)

La différence de mon script c'est qu'il ne passe pas par des boutons radios (donc pas par un formulaire). Ca change pas grand chose m'enfin bon...
C'est par un système de lien MEME SI le javascript n'est pas activé :p
Par contre je pourrais par la suite développer un plugins jquery qui va avec wink !
Et ma rating bar montre la note moyenne en plus. Par contre je retins l'idée du 0 différentiable.

Je pense donc à faire une classe spécifique avec éventuellement db adaptater et un controller générique. Jeviens aussi de penser à un fichier de config ini (ou xml, ou les 2). Faut travailler ça.
Je vais partir la dessus. Mais n'hésiter pas à rajouter votre touche (ou idées comme on veut smile )

Hors ligne

 

Pied de page des forums

Propulsé par PunBB
© Copyright 2002–2005 Rickard Andersson
Traduction par punbb.fr

Graphisme réalisé par l'agence Rodolphe Eveilleau
Développement par Kitpages