Models
In HivePress, models are PHP classes used as wrappers for WordPress post types, comment types and taxonomies. With models, you can easily create, retrieve, update and delete any database entries in the same way without worrying about data validation and storage.
Let's take a look at the main operations you can perform on models. We use the Listing
model in the examples below, but the API is the same for all models. You can always check the available models in the includes/models
subdirectory of HivePress or its extensions.
Quick example
The code example below creates a new listing in the database, then the listing is marked as featured, and finally, the listing is deleted.
Creating objects
To create a model object, create a new instance of the HivePress\Models\{Model_Name}
class and call the fill
method with an array of field values. You can check the available fields in the model class file or invoke the _get_fields
method that returns an array of field objects. The model object will not be saved in the database until you call the save
method:
If the object is not saved (e.g. some required fields are empty), you can check the value returned by save
(instead of calling it separately) and get an array of validation errors:
After the object is saved in the database, it gets a unique ID:
Retrieving objects
To retrieve a model object from the database, simply query it by ID. Please refer to the Making Queries page if you want to retrieve multiple objects at once.
After you retrieve an object, you can get any field value by calling the get_{field_name}
method:
Also, you can use has_{field_name}
and is_{field_name}
aliases for better code readability:
To get the formatted field value, use the display_{field_name}
method instead:
If a field references another model object, you can access its field values via the double underscore:
To get an array of all the field values, use the serialize
method:
Updating objects
Call the set_{field_name}
method to set the field value:
If a field references another model object, you can use its ID as a value:
To set multiple fields at once, call the fill
method with an array of values:
There are a few ways to save changes in the database. You can call the save
method without arguments to save all fields, pass an array of field names to save, or save a single field by calling the save_{field_name}
method:
Also, you can chain methods for better code readability:
Deleting objects
To delete a model object from the database, call the delete
method:
Check the method result if you want to make sure that the object is deleted:
Also, models that inherit the Post
or Comment
classes can be moved to Trash:
Last updated