Custom page methods

2.3.0 +

Custom page methods vs. page models

Page models are a great way to create an extended version of the default page object with additional methods and functionalities. But a page model is tied to a specific template, while custom page methods apply to all page objects. If your use case is based on one specific template, a page model might be the better solution. If you have methods that should be available for all page objects in all templates, a custom page method is the way to go.

Default page methods

For a full list of default page methods, please check out the cheat sheet. Be aware that - contrary to page models - custom page methods cannot override default page methods.

Getting started

You can extend the set of defined page methods very easily. The best place to do this is in a plugin file: /site/plugins/page-methods.php

page::$methods['linktag'] = function($page) {
  return '<a href="' . $page->url() . '">' . $page->title()->html() . '</a>';
};

This example shows the basic architecture of a page method. You define the method name with the key for the page::$methods array. The callback function receives the $page object as first argument.

Return options

There are two common scenarios, what page methods can do:

1. Modifying the page

page::$methods['likeIt'] = function($page) {
    $page->increment('like');

    return $page;
};

If you want to make it possible to chain page methods and that the page can be further modified by other page methods, you must modify the page and then return the page object.

Example

<?= $page->likeIt()->hide() ?>

2. Returning info about the page

page::$methods['has5Siblings'] = function($page) {
    return $page->siblings()->count() == 5;
};

Page methods can also be used to make if clauses easier.

Example

<?php if($page->has5Siblings()) ?>
The page has 5 siblings.
<?php endif ?>

Working with method arguments

In some cases it might be helpful to be able to pass arguments to the method:

<?= $page->isSiblingOf($otherPage) ?>

The definition for such a method with arguments is very simple:

page::$methods['isSiblingsOf'] = function($page, $otherPage) {
    return $otherPage->siblings()->has($page);
};