Friday, December 14, 2018

Active Record Pattern



An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

An object carries both data and behavior. Much of this data is persistent and needs to be stored in a database. Active Record uses the most obvious approach, putting data access logic in the domain object. This way all people know how to read and write their data to and from the database

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.

This pattern is commonly used by object persistence tools and in object-relational mapping (ORM). 

The interface of an object conforming to this pattern would include functions such as Insert, Update, and Delete, plus properties that correspond more or less directly to the columns in the underlying database table.




An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.







An object carries both data and behavior. Much of this data is persistent and needs to be stored in a database. Active Record uses the most obvious approach, putting data access logic in the domain object. This way all people know how to read and write their data to and from the database.

Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated, the corresponding row in the table is also updated. The wrapper class implements properties for each column in the table or view.

This pattern is commonly used by object persistence tools and in object-relational mapping (ORM). Typically, foreign key relationships will be exposed 

For example, if in a database there is a table parts


part = new Part()
part.name = "Sample part"
part.price = 123.45
part.save()
will create a new row in the parts table with the given values, and is roughly equivalent to the SQL command
INSERT INTO parts (name, price) VALUES ('Sample part', 123.45);
Conversely, the class can be used to query the database:

b = Part.find_first("name", "gearbox")
This will find a new Part object based on the first matching row from the parts table whose name column has the value "gearbox". The SQL command used might be similar to the following, depending on the SQL implementation details of the database:
SELECT * FROM parts WHERE name = 'gearbox' LIMIT 1; -- MySQL or PostgreSQL

Testability[edit]

Due to the coupling of database interaction and application logic when using the active record pattern, unit testing an active record object without a database becomes difficult.[citation needed] The negative effects on testability in the active record pattern can be minimized by using mocking or dependency injection frameworks to substitute the real data tier with a simulated one

Single responsibility principle and separation of concerns[edit]

Another critique of the active record pattern is that, also due to the strong coupling of database interaction and application logic, an active record object does not follow the single responsibility principle and separation of concerns 
Because of this, the active record pattern is best and most often employed in simple applications that are all forms-over-data with CRUD functionality,

Distributed systems[edit]

Record based patterns work poorly in distributed systems especially where concurrency is impossible ( eg offline ). i.e. 2 updates both may have 1 field that is correct but only one of the 2 records can win

Active Record

An object that wraps a row in a database table, encapsulates the database access, and adds domain logic on that data.

Active Record = Row Data Gateway + Domain Logic

!php
$con = new Connection('...');

$banana = new Banana();
$banana->setName('Another banana');
$banana->save($con);

// Call a method that is part of the domain logic
// What can a banana do anyway?
$banana->grow();

// Smart `save()` method
// use `isNew()` under the hood
$banana->save($con);

Active Record

!php
class Banana
{
    private $height = 1;

    public function grow()
    {
        $this->height++;
    }

    public function save(Connection $con)
    {
        if ($this->isNew()) {
            // issue an INSERT query
        } else {
            // issue an UPDATE query
        }
    }

    public function isNew()
    {
        // Yoda style
        return null === $this->id;
    }
}

The interface of an object conforming to this pattern would include functions such as Create, Read, Update, and Delete, that operate on objects that represent domain entity types in a data store.







Active record pattern

An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

How it works

An object is directly related to the row in a table or view. It is very similar to the Row data gateway pattern except that it contains the behavior of the object (as well as the data).

When to use it

Simple objects with simple business rules.

Example

Active record.png

No comments:

Post a Comment