[Design Patterns]: Active Record

Database table or view will be mapped into an object.

Drawbacks:
* objects are tightly coupled to the database schema
* objects are tightly coupled to the database itself

Example:

class User
{
   protected $connection = null;

   public function __construct()
   {
      $this->connection = new PDO("mysql:host=localhost;dbname=development", 'root', 'root');
   }

   public function load($id)
   {
      $sql = 'SELECT * FROM users WHERE user_id=' . (int)$id;
      $result = $this->connection->query($sql);
      $row = $result->fetch(PDO::FETCH_ASSOC);

      foreach ($row as $column => $value) {
         $this->column = $value;
      }
   }
}

$user = new User();
$user->load(2);

print_r($user);

Majd Arbash

Leave a Reply