🔹 Active Record in Object-Oriented Programming (OOP)
**Active Record** is a design pattern used in Object-Oriented Programming (OOP) for handling **database interactions**. It simplifies data access by treating **database rows as objects** and **tables as classes**.
📌 Why Use Active Record?
Active Record provides a **structured and efficient way** to interact with databases.
- ✅ **Easier Database Operations** – Perform CRUD (Create, Read, Update, Delete) operations without writing SQL queries.
- ✅ **Encapsulation** – Keeps database logic inside model classes.
- ✅ **Reduces Code Duplication** – Database interactions are handled in one place.
- ✅ **Object-Oriented Approach** – Works well with OOP principles.
💡 Real-Life Example
Imagine a **Users table** in a database. Each user is treated as an object in the program:
- 🔹 **User (Object)** → Represents a row in the database.
- 🔹 **Attributes** → Name, Email, Age.
- 🔹 **Methods** → Save(), Update(), Delete().
🖥️ Active Record in Ruby on Rails
Active Record is widely used in **Ruby on Rails** for database management.
class User < ApplicationRecord
# Retrieves all users
def self.get_users
User.all
end
end
🖥️ Active Record in PHP (Laravel)
Laravel uses the **Eloquent ORM**, which follows the Active Record pattern.
class User extends Model {
// Retrieve all users
public static function getUsers() {
return self::all();
}
}
🖥️ Active Record in Java (Hibernate)
Hibernate ORM in Java implements the Active Record pattern.
@Entity
class User {
@Id
@GeneratedValue
private Long id;
private String name;
private String email;
// Getter and Setter methods
}
🎯 Summary
Active Record makes database operations **simpler and object-oriented**. It is widely used in frameworks like **Ruby on Rails, Laravel, Django, and Hibernate**.