Based on the blueprint + model for album in Starterkit,
My aim is to have three separate pages - portfolio pieces, perspectives, and life (news) - and inside each of those would be any number of individual album-like pages.
I have created blueprints for the page and section for portfolio pieces, and a blueprint for portfolio. They have have adapted directly from the Starterkit album files. This much appears to be working as expected.
On the template for home.php, I can call the individual portfolio pages into the front-end. All of the object data appears to be well-formed and intact.
When I attempt to copy and adapt the album model for portfolio, I’m getting really stuck.
My aim is to adapt the Cover method so each portfolio object automatically renders out the selected cover file as an image. But I’m not sure what I’m overlooking.
Any thoughts…?
→ models\portfolio.php
class PortfolioPage extends Page{
public function coverPortfolio() {
// need to verify whether $this refers to the correct context for my purposes
return $this->content()->get(‘cover’)->toFile() ?? $this->image();
}
}
Both models return an image object (if it exists), if you echo an image object, it returns the HTML (I corrected my example above).
The reason for this is the magic __toString() method that creates an image tag for an image file in a string context:
The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.
This is the method (in FileFoundation.php)
public function __toString(): string
{
if ($this->type() === 'image') {
return $this->html();
}
return $this->url();
}
Anything thoughts on how I can diagnose why I’m seeing different results?
In the attached screen capture, both the album and the portfolio objects are being printed using PHP, and the respective cover and coverPortfolio models called.
The album cover is being returned as a fully-formed piece of HTML, but the portfolio coverPortfolio only returns the filename…
But taking on board your advice regarding Page Models, I can see why the call to coverPortfolio would not be connecting to the actual coverPortfolio method.
It’s Australia over here, so everything is upside down
If this code appears inside home.php, is it enough that we’re calling in page(‘portfolio’) as the parent object? Will Kirby make the connection between page(‘portfolio’) and models/portfolio.php?