WordPress Data
Every component has two PHP files responsible for hydrating and managing component side effects,
class-model.php- Used to hydrate a component with values from WordPress.class-controller.php- Used to apply PHP side effects, like hooks and filters that should only run for specific components.
Model
Lifecycle
When a Nova template component is loaded, it'll kick off the hydration process by calling the model for that template. Each child component will then have their models called, and so on.
The result is an object which validates against the template schema.
Example
<?php
/**
* Model for the `example` component.
*
* @package pmc-nova
*/
declare( strict_types = 1 );
namespace PMC\Nova\Style_Guide\Components\Article_Footer;
use PMC\Nova\Components\Model as Base;
use PMC\Nova\Style_Guide\Components;
/**
* Class Model.
*/
final class Model extends Base {
/**
* Post ID to populate data from.
*
* @var int
*/
public int $post_id;
/**
* Populate data structure.
*/
protected function _populate_data(): void {
// Set a data value directly.
$this->_data->text = 'Hello World';
// Set a data value using a component.
$this->_add_nested_model_data(
'comments',
Components\Comments\Model::class,
[
'post_id' => $this->post_id,
]
);
}
}Properties
The class properties in a model are used to pass state/context from a parent.
For example, the $post_id needs to be passed down from <TemplateArticle /> to its child component, <ArticleHeader />, which then uses the $post_id to get the post title, and passes it to a <Text /> component,
// template-article/model.php
final class Model extends Base {
/**
* Post ID to populate data from.
*
* @var int
*/
public int $post_id;
/**
* Populate data structure.
*/
protected function _populate_data(): void {
$this->_add_nested_model_data(
'articleHeader',
Components\Article_Header\Model::class,
[
'post_id' => $this->post_id,
]
);
}
}// template-article/model.php
final class Model extends Base {
/**
* Post ID to populate data from.
*
* @var int
*/
public int $post_id;
/**
* Populate data structure.
*/
protected function _populate_data(): void {
$this->_add_nested_model_data(
'postTitle',
Components\Text\Model::class,
[
'text' => get_the_title( $this->post_id )
]
);
}
}