Extending Kirby models

Ever since Kirby introduced a default model in version 4, I have been handling things like the OG image and the SEO title in there.

I really like this approach. It just feels right to put stuff like that in the model. With a system like Kirby, there are always at least 10 different ways of doing things. You could put it in a controller, in a page method, in a snippet, in a plugin, … but in my experience, a model is the best fit.

In this article I want to share a quick tip on how to extend the default model. It’s a simple thing, but it took me a while to figure it out so I thought it might be helpful to others.

My default model

<?php

use Kirby\Cms\Page;
use Kirby\Cms\File;

class DefaultPage extends Page
{

    public function seoTitle(): string
    {
        $siteTitle = $this->site()->title();
        $pageTitle = $this->title_seo()->or($this->title());

        return "{$pageTitle} · {$siteTitle}";
    }

    public function ogImage(): ?File
    {
        // 📝 Try page-specific OG image first
        $pageImage = $this->og()->toFile();
        if ($pageImage) {
            return $pageImage;
        }

        // 🌐 Fallback to site-wide OG image
        $siteImage = $this->site()->og()->toFile();
        if ($siteImage) {
            return $siteImage;
        }

        return null;
    }
}

Surprisingly, I rarely need more than one model. I just put everything in the default model. However, I recently needed to customize the OG image generation for a specific page type while maintaining the rest of the default functionality. The solution turned out to be straightforward, though it wasn’t immediately obvious.

The (admittedly simple) solution:

<?php

// Require the default model
require_once kirby()->root('models') . '/default.php';

// Extend the default model
class ArticlePage extends DefaultPage
{

// seoTitle() and ogImage() methods are inherited
// Add or override specific methods as needed

}

Learning in public

This is my first “TIL” (Today I Learned) post. I want to make it a habit to publish quick tips and small discoveries regularly. If you found this helpful, I’d love to hear from you on Mastodon.