Question

Why a Product object, for example, has a method called Save?

It seems to me that it is wrong for a Product saving yourself in the database. A product should not only know only about their own responsibility? Did I not understand the purpose of AR or the problem is not in my interpretation?

$product = new Product();
$product->name = 'sample post';
$product->price = 10;
$product->save();
Was it helpful?

Solution

The general principle of Active Record is that an instance of an object is a single row in the data store and the object is wholly responsible for the persistence of itself.

The object has a single responsibility and that is manage the persistence of itself.

Martin Fowler says it best:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top