WordPressMVC

  1. Get Started
  2. Documentation
  3. Tutorials
  4. Blog
  1. Documentation
  2. Tutorials
v1.0.8 Login
  • Blog
  • Download
  • Get Started
  • The Basics
    • Ayuco
    • Main Class
    • Configuration
  • Hooks
    • Actions
    • Filters
    • Widgets
    • Shortcodes
  • MVC
    • Models
    • Post Models
    • Option Models
    • Term Models
    • User Models
    • Views
    • Controllers
  • Resources
    • Assets
    • Styles
    • Scripts
  • Advanced
    • Request
    • Response
    • Localization
    • Cache
    • Logger
    • Database
    • Testing
    • Deployment
    • Functions
    • Add-ons

Post Models

Last updated: February 9, 2023

Post Models are a type of model that can be created using the framework.

Model Functionality

Out-of-the-box will provide methods to save, delete and get information to and from Wordpress database without any complex development needed. The model's attributes (or data columns) can be accessed as object properties.

Ayuco Command

Create command

Create command is used when the post type related to the model is already defined in Wordpress (i.e. pages, posts, and attachments).

php ayuco create model:{model}
{model}The name of the class model to be created.

Register command

Register command is used when a new post type needs to be registered and needs to be related to a model (i.e. books, products, artists and others).

php ayuco register type:{type} {model} {controller}
{type}The custom post type to be registered.
{model}The name of the class model to be created.
{controller}Controller for automated property saving.

Usage

Add the use statement at the beginning of your PHP files to specify which model you’ll use in your code.

// Definition to use "Post" model.
use MyNamespace\Models\Post;

// Definition to use "Book" model.
use MyNamespace\Models\Book;

// Usage in variables after definition.
$post = Post::find( $post_id );
$book = new Book;

Get

There are two methods that can be used to retrieve models loaded with data:

  • find() used to retrieve an individual record. Pass by a Post ID as a parameter.
  • from() used to retrieve child records from a post parent. Pass by a Post ID (parent ID) as a parameter.
/**
 * Find and get the post model with ID "1" from database.
 * @return {object} Post model loaded with data from post "1".
 */
$post = Post::find( 1 );

/**
 * Find and get all attachments related to the previous post from the database.
 * @return {array} Collection of attachments related to post.
 */
$attachments = Attachment::from( $post->ID );

Save

Saving the information of a model is a piece of cake, simply call the save() method. This will insert or update the record in the database.

// First we modify some of the attributes in the model.
$post->post_title = 'My awesome post';
$post->post_content .= ' This is appended to the content.';

// Then we save changes
$post->save();

Delete

Deleting a model is easy, simply call the delete() method to move the record to the Wordpress trash.

$post->delete();

Add the $forceDelete property inside the model to force database deletions (no trash).

use WPMVC\MVC\Traits\FindTrait;
use WPMVC\MVC\Models\PostModel as Model;

class Post extends Model
{
    use FindTrait;
    
    /**
     * Forces database deletions instead of just
     * moving the record to Wordpress trash.
     * @var bool
     */
    protected $forceDelete = true;
}

Aliases

Arguably, the most powerful feature in a model. The $aliases property serves as a mapping tool between custom aliases and post attributes, meta values and/or custom functions. Defined aliases can be later accessed as regular properties in a loaded model.

use WPMVC\MVC\Traits\FindTrait;
use WPMVC\MVC\Models\PostModel as Model;

class Post extends Model
{
    use FindTrait;

    /**
     * Aliases.
     * Mappaed against post attributes, meta data or functions.
     * @var array
     */
    protected $aliases = [
        // Alias "title" for post attribute "post_title"
        'title'     => 'post_title',
        // Alias "editor" for meta data with meta key "editor"
        'editor'    => 'meta_editor',
        // Alias "date" for meta data with meta key "publish_date"
        'date'      => 'meta_publish_date',
        // Alias "author" for class function "get_author"
        'author'    => 'func_get_author',
    ];
    
    /**
     * Returns the values used for alias "author".
     * In this example, this function will return the fullname of
     * an author based on meta data stored in the model.
     * @return string
     */
    public function get_author()
    {
        return $this->meta['author_name'].' '.$this->meta['author_lastname'];
    }
}

Alias usage sample:

$post = Post::find(1);

/**
 * (1) Echo the value stored on "post_title" attribute.
 * (2) Update the value stored  on "post_title" attribute.
 */
echo $post->title;
$post->title = 'New title';

/**
 * (1) Echo the meta value stored on meta key "editor".
 * (2) Update the meta value stored on meta key "editor".
 */
echo $post->editor;
$post->editor = 'Wordpress MVC';

/**
 * (1) Echo the meta value stored on meta key "publish_date".
 * (2) Update the meta value stored on meta key "publish_date".
 */
echo $post->date;
$post->date = date('Y-m-d');

/**
 * (1) Echo the returned value of function "get_author".
 * (2) Aliases based on functions are READ-ONLY
 */
echo $post->author;

// Save updates made on model.
$post->save();

Be aware

Aliases mapped to meta data must be defined using prefix meta_ followed by the meta key. Aliases mapped to functions must be defined using prefix func_ followed by the name of the function in the class. Functions based aliases are READ-ONLY.

Meta Data

All the metadata is loaded when a model is retrieved from the database, this information can be accessed with the property meta.

/**
 * Use the "meta_key" of choice to access the desired
 * meta value. This property is READ-ONLY, to make meta
 * writable use aliases instead.
 * @var array
 */
$post->meta['meta_key'];

Is READ-ONLY

meta is READ-ONLY, to make meta writable use aliases instead.

Casting

The model can be cast (converted) into multiple data types.

// Casts model to array.
$array = $post->to_array();

// Casts model to WP_Post object.
$wp_post = $post->to_post();

// Casts model to json string.
$json = $post->to_json();

// Casts model to json string.
$string = (string)$post;

To hide properties (attributes or aliases) from appearing on JSON or array formats (when casting) add the $hidden property inside your model class.

class Post extends Model
{
    use FindTrait;

    /**
     * Hidden properties.
     * Removed properties/aliases when model
     * is casted into json, string or array.
     * @var array
     */
    protected $hidden = [
        'post_date',
        'password',
    ];
}

Automated

Automated models are used to register new post types and simplify meta box editing. This type of model is linked to a Model Controller.

This type of model supports additional properties to handle automation. Property $registry_controller defines the controller in charge of handling meta box and saving. Property $registry defines the basic post_type registration. Property $registry_labels defines the labels for the new post type. Property $registry_supports defines the list of WordPress features the post supports. Property $registry_rewrite defines rewrite rules for the new post type. Property $registry_taxonomies defines taxonomies as the new post type. Property $registry_metabox defines the meta box arguments in which custom metadata will display in the post edit page.

class Book extends Model
{
    use FindTrait;

    /**
     * Post type
     * @var string
     */
    protected $type = 'book';

    /**
     * Controller in charge of automation.
     * @var string
     */
    protected $registry_controller = 'BookController';

    /**
     * Basic registry definition.
     * This sample shows the default settings.
     * MUST BE PUBLIC to work.
     * @var array
     */
    public $registry = [
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
    ];

    /**
     * Labels.
     * MUST BE PUBLIC to work.
     * @var array
     */
    public $registry_labels  = [
        'name'               => 'Books',
		'singular_name'      => 'Book',
		'menu_name'          => 'Books',
    ];
    
    /**
     * Wordpress support for during registration.
     * MUST BE PUBLIC to work.
     * @var array
     */
    public $registry_supports = [
        'title',
        'editor',
        'author',
        'thumbnail',
        'excerpt',
        'comments',
    ];
    
    /**
     * Rewrite.
     * MUST BE PUBLIC to work.
     * @var array
     */
    public $registry_rewrite = [
        'slug' => 'book'
    ];
    
    /**
     * Metabox.
     * MUST BE PUBLIC to work.
     * @var array
     */
    public $registry_metabox = [
        'title'             => 'Properties',
        'context'           => 'normal',
        'priority'          => 'high',
    ];
    
    /**
     * Taxonomies.
     * MUST BE PUBLIC to work.
     * @var array
     */
    public $registry_taxonomies = [];
}

Important to know

Not all registry properties need to be filled, use only those needed.

Relationships

Relationships between models can be done in 3 ways.

  • has one: 1 to 1 relationship that indicates that a model relates to another model as a parent.
  • belongs to: 1 to 1 relationship that indicates that a model relates to another model as a child.
  • has many: 1 to N relationship that indicates that a model relates to multiple models as a parent.

Has one (has_one) relationship

class Post extends Model
{
    use FindTrait;
    
    /**
     * Aliases.
     * @var array
     */
    protected $aliases = [
        'book_id'   => 'meta_book_id',
    ];

    /**
     * Returns "has_one" relationship.
     * @return object|Relationship
     */
    protected function book()
    {
        return $this->has_one( Book::class, 'book_id' );
    }
}

In the example above, model Post has a 1-to-1 relationship with model Book. The relationship is done through the post's alias book_id.

Relationship usage:

// Get post
$post = Post::find( $post_id );

// Display "book" relationship model
var_dump( $post->book );

The relationship system is so powerful that it lets you relate to external models (models coded outside the framework).

External relationship definition sample:

class Book extends Model
{
    use FindTrait;
    
    /**
     * Aliases.
     * @var array
     */
    protected $aliases = [
        'product_id'   => 'meta_product_id',
    ];

    /**
     * Returns "has_one" relationship with a woocommerce class model.
     * @return object|Relationship
     */
    protected function product()
    {
        return $this->has_one(
            WC_Product::class,
            'product_id',
            null, // Method to init in child class
            'wc_get_product' // Global function used to load class
        );
    }
}

In the example above, model Book has a 1-to-1 relationship with model WooCommerce's class model WC_Product. The relationship is done through the post's alias product_id and using the global function wc_get_product().

Belongs to (belongs_to) relationship

class Post extends Model
{
    use FindTrait;

    /**
     * Returns "belongs_to" relationship.
     * @return object|Relationship
     */
    protected function parent()
    {
        return $this->belongs_to( Post::class, 'post_parent' );
    }
}

Has many (has_many) relationship

class Post extends Model
{
    use FindTrait;
    
    /**
     * Aliases.
     * @var array
     */
    protected $aliases = [
        'event_ids' => 'meta_events',
    ];

    /**
     * Returns "has_many" relationship.
     * @return object|Relationship
     */
    protected function events()
    {
        return $this->has_many( Event::class, 'event_ids' );
    }
}

Use array

The property or alias used to create a relationship of type "has_many" needs to be an array with a list of the ids that will be used to load each of the related child objects.
© 2023 10 Quality Studio . All rights reserved.
Search in: