For the most part, the web applications we build house their data in a relational database. The blog posting application we used in the previous example holds blog post content in database tables. However, web applications need the data that is held in the persistent database storage mapped to in-memory class properties that define the domain objects. Object-relational mapping (ORM) libraries provide this mapping of database tables to domain object classes.
Much of the code that deals with ORM is about describing how fields in the database correspond to fields in our objects, which is tedious and repetitive to write. Luckily, Yii comes to our rescue to save us from this repetition and tedium by providing the ORM layer in the form of the AR pattern.
As was previously mentioned, AR is a design pattern used to abstract database access in an object-oriented fashion. It maps tables to classes, rows to objects and columns to object attributes. In other words, each instance of an active record class represents a single row in a database table. However an AR class is more than just a set of attributes that map to columns in a database table; it also houses the needed business logic behavior to be applied to that data. The end result is a class that defines everything about how it should be written to and read from the database.
By relying on convention and sticking with reasonable defaults, Yii's implementation of AR will save the developer a ton of time normally spent in configuration or in writing tedious and repetitive SQL statements required to create, read, update and delete data. It also allows the developer to access data stored in the database in a much more object-oriented way. To illustrate this, here is some example code that uses AR to operate on a specific blog posting whose internal id, which is also used as the table's Primary Key, is 99
. It first retrieves the posting by Primary Key, it then changes the title, and then updates the database to save the changes:
$post=Post::model()->findByPk(99); $post->title='Some new title'; $post->save();
Active Record completely relieves us of the tedium of having to write any SQL or otherwise deal with the underlying database.
Note
Active Record does even more than this. It integrates seamlessly with many other aspects of the Yii Framework. There are myriad active html helper input form fields that tie directly to their respective AR class attributes. This way, Active Record extracts the input form field values directly into the model. It also supports sophisticated, automated data validation, and if the validation fails, the Yii view classes easily display the validation errors to the end user. We will be revisiting AR and providing many concrete examples throughout this book.