views:

112

answers:

2

I have a smaller web app that republishes content from one social source to another. Users have, let's say 5 options for how to filter that content. Their prefs are stored in my user DB as 1 or 0 markers.

When I do my major "publish" action hourly, what's the best way to break up my code to implement these preferences? To make it more clear, my current implementation is something like this:

mysql_query(SELECT * FROM users);
foreach ($user as $row){
    get_json_data($userID);
    if ($pref1 == 1){
        /code that enacts preference 1, adds results to array $filtereddata
    }
    if ($pre2 == 1 ){
        /code that filters out preference 2, adds results to $filtereddata
    {   
    postfinalarray($filtereddata);
}

Obviously this is mock code, but that's the general flow I've been using. Is there a better way to implement customizing a function with user's preferences? Should I design the function to accept these preferences as parameters? Will that save processing time or be more maintainable?

Sorry if this is too general, please ask questions so I can clarify.

+1  A: 

Well of course there are many possibilities to improve this kind of code. Just imagine, if you would add another preference you would have to rewrite your whole code. I always try to use the object oriented way so creating a user class always makes sense:

<?php

class User
{
    private $_data;

    public function __construct($userdata, $preferences)
    {
     $this->_data = $userdata;
    }

    public function getPreferencesData($preferences)
    {
     $result = array();
     $prefs = $this->_data['preferences'];
     foreach($preferences as $key => $value)
     {
      if($value == "1")
       $result[] = $this->_data[$key];
     }
     return $result;
    }
}

$mypreferences = array("name" => 1, "birthdate" => 0); // show e.g. name and birthdate
$mydata = array("name" => "Gaius Julius Caesar", "birthdate" => "July 13th -100");
$testuser = new User($mydata);
print_r($test->getPreferencesData($mypreferences));

?>

Then you can easily adapt to whatefer preferences the user has chosen without having to change your code.

Daff
A: 

From the limited info you've provided, your method seems fine.

I would do something slightly different probably. I would have a table of your 5 prefs (or would just hard code them if they're very unlikely to change). I would create a cross-reference table linking the prefs and users. Then you can do something like:

foreach($users as $user)
{
    $filtereddata = array();
    foreach($user->getPreferences() as $pref)
    {
        $filtereddata += $this->getFilteredData($user, $pref);
    }
}

This is more overhead than what you're using, but more easily extensible if/when you add preferences/features.

Scott Saunders