samedi 2 mai 2015

Right way to handle database access in PHP OOP

I need some help with database access in PHP. I'm trying to do things the OOP way but I'm not sure if I'm heading the right way.

Lets say I have a class Person, for example:

class Person {
    private $id;
    private $firstname;
    private $lastname;
    // maybe some more member variables

    function __construct($id = NULL) {
        if(isset($id)) {
            $this->id = $id;
            $this->retrieve();
        }
    }

    // getters, setters and other member functions

    private function retrieve() {
        global $db;

        // Retrieve user from database
        $stmt = $db->prepare("SELECT firstname, lastname FROM users WHERE id = :id");
        $stmt->bindParam(":id", $this->id, PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetch();

        $this->firstname = $result['firstname'];
        $this->lastname = $result['lastname'];
    }

    function insert() {
        global $db;

        // Insert object into database, or update if exists
        $stmt = $db->prepare("REPLACE INTO users (id, firstname, lastname) VALUES (:id, :firstname, :lastname)");
        $stmt->bindParam(":id", $this->id, PDO::PARAM_INT);
        $stmt->bindParam(":firstname", $this->firstname, PDO::PARAM_STR);
        $stmt->bindParam(":lastname", $this->lastname, PDO::PARAM_STR);
        $stmt->execute();
    }
}

Note that this is just an example I just wrote to describe my question, not actual code I use in an application.

Now my first question is: is this the correct way to handle database interaction? I thought this would be a good way because you can instantiate an object, manipulate it, then insert/update it again.

In other words: is it better to handle database interaction inside the class (like in my example) or outside it, in the code that instantiates/uses the class?

My second question is about updating a whole bunch of rows that may or may not have been modified. Lets say the class Person has a member variable $pets[], which is an array containing all the pets that person owns. The pets are stored in a separate table in the database, like this:

+---------+-------------+---------+
|  Field  |    Type     |   Key   |
+---------+-------------+---------+
| pet_id  | int(11)     | PRI     |
| user_id | int(11)     | MUL     |
| name    | varchar(25) |         |
+---------+-------------+---------+

Lets say I modified some pets in the Person object. Maybe I added or deleted some pets, maybe I only updated some pet's names.

What is the best way to update the whole Person, including their pets in that case? Lets say one Person has 50 pets, do I just update them all even if only one of them has changed?

I hope this is clear enough ;)

What is the proper design pattern for parsing an expression of the type [A][B][A][B]....[B][A]?

I'm making an algorithm that parses a mathematical function into a function tree. The idea behind it is that the function, represented as a string, will look like

[expression][operator][expression][operator]...[operator][expression]

and my algorithm will be like

  1. Get first expression
  2. Make first expression be the root of the tree
  3. While not at end of string, get operator and expression following it. Add expression to its proper place in the tree.

Get last operator and expression following it

I've outlined what's going to happen in the comments of the below code.

node * buildTree ( char * str )
{
/*
    str is expected to be of the form 

        [expr_0][op_1][expr_1][op_2][expr_2]...[op_n][expr_n]

    For example, 

        "x^2*(5+x)"

    has 
        expr_0 = "x",
         op_1  = "^"
        expr_1 = "2"
         op_2  = "*"
        expr_2 = "(5+x)"

    The function expressions are represented as node elements. Returns the root of the function
    tree that is built.
*/

    node * rt; // Node to return, the root of the function tree
    node * thisExpr; // Current function
    char thisOp; // Current operator

    /* The beginning of str is expected to be a function expression (rather than an operator). 
       The following sets thisExpr equal to that expression and advance the pointer str to the character following it.
    */
    if (!throughNextExpr(&str, &thisExpr))
    {
        return NULL;
    }
    else
    {
        rt = thisExpr;
    }

    while (str)
    {
        /* Current caracter is expected to be an operator. Set thisOp equal to it and advance to the next character 
        */
        thisOp = *str;
        if (indexOf(thisOp, opstack) == -1)
        {
            return NULL;
        }
        ++str;
        /* Current character is expected to be the beginning of an expression. Set thisExpr equal to it and avance to the character following the epxression
        */
        if (throughNextExpr(&str, &thisExpr))
        {
            // ...
        }
        else // error in trying to get next expression
        {
            return NULL;
        }

    }
    return rt;
}

int throughNextExpr ( char * * str, node * * N )
{
    int goodSoFar = 1;
    // .... Yet to be implemented
    return goodSoFar;
}

The problem is that this seems like very unelegant way of doing things, since getting the first expression is separated from the loop that gets the others. I feel like there should be a way of doing this all in a loop rather than separating into cases. Is there a known design pattern that I should be looking at instead?

Creating a list of booleans on the fly

Imagine we are pulling data about people and their favourite foods.
The data would come to us in the format: "Name, FavFood1, FavFood2..FavFoodn".
e.g. "James, Beans, Chicken".
Notice how we do not know how many foods a person will favour.

From this data we create an instance of a Person object which captures the person's name and favourite foods.
After we have pulled data on every person, we want to create a spreadsheet whose columns would be: Name|Potato|Chicken|Beans|Curry etc.
All of the values to the right of the person's name will be simple boolean values representing whether or not that food was one of the person's favourites.
The problem is: we do not know in advance; all the foods that someone could possibly favour, and as such cannot just set up boolean instance variables in the Person class.

I've given this some thought, implementing sets,hash-sets and hash-maps, however every solution I think of ends up being horribly inelegant and so I've turned to the genius of stackoverflow for help on this one.
My question is: What design pattern / approach can I use to cleanly achieve the outcome I desire?
Whilst this is a language-agnostic question I am programming this in Java, so if there's anything in the Java API or elsewhere built for this, do let me know.
Thanks in advance!

In a two-class three-dimensional classification find the equation of decision boundary.

I've just started learning Pattern Recognition and I am kind of stuck at this homework assignment, any help will be appreciated. Thank you.

In a two-class three-dimensional classification problem, the feature vectors in each class are normally distributed with same co-variance matrix

 | 0.3  0.1  0.1 |
 | 0.1  0.1 -0.1 |   = Σ  
 | 0.1 -0.1  0.3 | 

The respective mean vectors are [0, 0, 0]t and [0.5, 0.5, 0.5]t. Find the equation of the decision boundary. Assume equal a-priori probabilities.

Wildcard capture in Java, unable to call a method

I currently have three classes and trying to implement Generic Visitor pattern for putting it into a library shared among all our projects:

public interface Visitable<ReturnType> {

    public ReturnType accept(Visitor<?, ?> v);

}

public interface Visitor<SomeVisitable extends Visitable<?>, ReturnType> {

    public ReturnType visit(SomeVisitable v);

}

public class BaseObject implements Visitable<Void>{
    public Void accept(Visitor<?, ?> v) {
        v.visit(this); //1
                       // The method visit(capture#1-of ?) in the type                                        
                       // Visitor<capture#1-of ?,capture#2-of ?> is not
                       // applicable for the arguments (BaseObject)
    }
}

Why did I get the compile-time error at //1? Honestly I really don't know what I should redisign in that code to make it compile.

Most used php design patterns at day to day basis?

In order to improve development skills im wondering what are the most often used php patterns on a day to day basis in development and its general purposes

I may start the list with the classics of all the time:

  • Sigelton (may consired a semi pattern)
  • Factory (an is variants as factory method)
  • Mememto (to save status of something at runtime...)

I know the are many more, but they are used with regularity?

Thanks in advice!

Examples of Hexagonal Architecture (Ports and Adapters) in open source projects, mainly web oriented

I'm reading "Growing Object-Oriented Software, Guided by Tests" and I wonder if someone knows of open source projects I could use to better grasp this design pattern. So far I'm only aware of little demos, more like conceptual exercises.

Thanks!