Archive for February 2010

Bean Pattern in PHP5


Taking advantage of PHP5′s magic methods __get, __set, and __call, the bean pattern can be implemented pretty easily in PHP. Here’s an example of it in Java:

public class UserBean {

    protected String username, email, location;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    public String getLocation {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
}

One of the annoyances of this (at least for me) is that you end up creating a bunch of getter/setter methods that don’t do anything special – they either return the encapsulated variable or set it. So, I wrote a base class that uses PHP5′s magic methods to take care of all of those generic getters and setters. (more…)