1.4. User Class

The majority of the code written maintaining a user's account can be encapsulated into one data structure, making it easy to extend or reuse in future applications. This includes the database interaction logic, which will make storing and retrieving information easier. Here's User.php:

<?php
class User
{
    private $uid;     // user id
    private $fields;  // other record fields

    // initialize a User object
    public function __construct()
    {
        $this->uid = null;
        $this->fields = array('username' => '',
                              'password' => '',
                              'emailAddr' => '',
                              'isActive' => false);
    }

    // override magic method to retrieve properties
    public function __get($field)
{ if ($field == 'userId') { return $this->uid; } else { return $this->fields[$field]; } } // override magic method to set properties public function __set($field, $value) { if (array_key_exists($field, $this->fields)) { $this->fields[$field] = $value; } } // return if username is valid format public static function validateUsername($username) { return preg_match('/^[A-Z0-9]{2,20}$/i', $username); } // return if email address is valid format public static function validateEmailAddr($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } // return an object populated based on the record's user id public static function getById($user_id) { $user = new User(); $query = sprintf('SELECT USERNAME, PASSWORD, EMAIL_ADDR, IS_ACTIVE ' . 'FROM %sUSER WHERE USER_ID = %d', DB_TBL_PREFIX, $user_id); $result = mysql_query($query, $GLOBALS['DB']); if (mysql_num_rows($result)) ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.