Access Methods From Another Page Model in Kirby CMS
The Situation
I created a Kirby CMS Plugin based on the virtual page guide.
In this example, I send requests to several (or one) API endpoints to build a list products (ProductsPage->children()
).
class ProductPage extends Kirby\Cms\Page
{
public function getProducts(){
return $request = Remote::get($url)->json();
}
public function getAttribute($id){
return $request = Remote::get($url . '?id=' . $id)->json();
}
}
class ProductsPage extends ProductPage
{
public function children(){
$products = $this->getProducts();
$pages = [];
foreach ($products as $key => $product) {
$pages[] = [
'slug' => Str::slug($product->title),
'num' => $key+1,
'template' => 'product',
'model' => 'product',
'content' => [
'title' => $product->title,
'attribute' => $this->getAttribute($product->id)
]
];
}
return Pages::factory($pages, $this);
}
}
This is all self-contained and serves this one purpose.
But now I want to use some of that products' data from the API, on another page or in another Kirby Plugin. And one way would be to replicate the API requests, or there is a way to load that ProductPage
model into my new model. And that can be easily done by querying the page and use its public methods.
class DataPage extends Kirby\Cms\Page
{
public function children(){
$attribute= page('product/data')->getAttribute($id);
$pages = [];
return Pages::factory($pages, $this);
}
}