Test whether a page is a virtual page?

Hi. I am experimenting with creating virtual pages from a sqlite database; all working as expected, using the comprehensive guide on the topic. The pages are created with Pages::factory, so they are “real” virtual pages (not just routes).

I am wondering, is there a means (by design, or a suggested workaround) to check programmatically whether a Page object is a virtual page? …conceptually speaking, something like a page('foo')->isVirtual() method, giving me true/false?

One possible hack I could imagine is to check the file system whether the respective directory exists (= not a virtual page). But maybe there is a much smarter way I am missing?

(This could of course be done by checking for the template name etc. in a specific project, but I am working on a plugin, so aiming to find a generic approach.)

Since virtual pages have their own models, you can check if they are of the given class using is_a(), for example:

<?php if(is_a($page, 'AlbumPage')) {
  echo 'This is an AlbumPage model';
} ?>

But yes, that is a similar approach as checking for a given template.

1 Like

Thank you. For a universally applicable solution, I came up with this custom page method:

Kirby::plugin('my/page-methods', [
    'pageMethods' => [
        'isVirtual' => function () {
            return ! F::exists( $this->contentFile() );
        }
    ]
]);

Now $page->isVirtual() returns true for virtual pages :slight_smile:

Note, that a page is also a real page if the folder exists without a content file. While this scenario will not happen if you create pages only via the Panel but only if you create pages manually, it is still a possible scenario.

Indeed, I did not think of that; thanks for pointing it out! So this would cover those cases as well:

Kirby::plugin('my/page-methods', [
    'pageMethods' => [
        'isVirtual' => function () {
            return ! is_dir( $this->root() );
        }
    ]
]);

…from Kirby 3.3.5 up, Dir::exists can be used instead of is_dir.