Global access to user details

Hi,

I have a site where I need to know whether a user is logged in, and what their role is, on nearly every page.

I currently am handling this in a site.php file in site/controllers.

This is working fine, but as I am currently refactoring the site I thought I would check if this was the best way to be doing this, especially as the site will probably be growing a fair bit.

Thanks for any insight.

Mike

Since you have access to the $kirby object in any template by default, you can access $kirby->user() everywhere. If you are using more logic around it that you don’t want in your templates, move it to controllers. If you find yourself repeating code too often in different controllers, you might want to move it to a plugin (https://www.youtube.com/watch?v=PajT4qyE55c)

In Kirby 5, the site controller will be merged with all regular controllers to offer another way to keep your code DRY. But for now, putting the code in a plugin might be the best.

Keep in mind though that accessing the user object in a controller or template will partly exclude that page from caching (because the user object relies on $kirby->session() internally).

So if you have entirely public pages that don’t depend on a logged-in user, those shouldn’t access the user object to increase performance. If you use the global site controller, it may make sense to add a condition that excludes those pages.

1 Like

This info is great, thank you. I will stick with a controller for now as that seems to be working well :dizzy: