Page Model vs. Controller

So both concepts are useful, however what is their distinction really?

With a Controller the documentation implies it is a way to return attributes for your page that are not as straight forward as listing them in the page.txt (articles/pagination).

With the Page Model it extends the Page object but the documentation shows a simple example of adding an extra attribute (cover in this case).

However both situations can be accomplished using either method.

So what is the preferred method? Or are they both to be used for different things?

For example I have a blog.php that currently is “the kitchen sink” and I am now separating its parts into Snippets, and whatnot.

In that blog.php I have a large chunk of PHP code at the top to collect together a lot of common information into PHP variables and also create two arrays of information. I do this so I do not have to keep querying Kirby every time I want to obtain some information.

So what should I use? Or should I be using both of them for different things?

In addition is one accessible from the other?

Thank you for any advice in advance,
D

Controllers and page models serve different purposes and there scope is different as well.

While controllers are only accessible from the templates with the same name, the methods of page models are also accessible from other templates that reference the page as well.

In your controllers, you put the logic - or the data - for your templates, thus keeping the template easier to read. So instead of defining your variables in the template, you do that in the controller, e.g.

$projects = page('projects')->children()->visible()->shuffle()->limit(5);

The page model, however, is useful if you want to define new page methods for your templates or if you want to overwrite/extend existing page methods. Typically, it makes sense to put a method into a page model, if it is used several times in a template or if you need a special function, i.e. a calculation.

For use cases of page models, you can search this forum a bit, e.g. this thread or this

This information would go into a controller.

3 Likes

Great thank you once again for the great explanation.

However I do have one issue (or misunderstanding).

It doesn’t 100% answer why the documentation has the Page Model example of adding a new attribute. In fact the example is exactly something that I am dealing with -> cover images (hero images).

From your explanation that should be a Controller issue not a Page Model One.

D

As @texnixe said, models provide their methods to all templates that reference the page. That’s why a custom mathod like in the docs can make sense.

I guess I understand the concept … I think the Page Model is what I will use for now and perhaps get an opinion at a later date.

Thank you once again,
D