Shared controller

A controller is always attached to a template.

I needed to have the same code in three different controllers. I felt bad about duplicating the code. It also felt strange to create a plugin and jump between the controller and the plugin.

Shared controller

In the controllers where you have duplicated code, (for example /site/controllers/home.php) do this:

require_once kirby()->roots()->controllers() . '/shared/my-shared-controller.php';

Try it out

In /site/controllers/shared/my-shared-controller.php add:

<?php
echo 'Shared controller';
die;

If it work, it will print “Shared controller” on the screen and nothing more.

Related topics

http://forum.getkirby.com/t/shared-controllers/1112
http://forum.getkirby.com/t/controller-for-whole-site/1732

11 Likes

Is there a way to return a variable with this method like we do in a normal page-specific controller?

Edit: I need to return search results on every page.

@lukehatfield What about using a route instead?

You could also use a function that gets the search results (but you would have to return the result from the controller to the template). But at least you wouldn’t have to repeat the complete logic. Not more code in the controller than including a shared controller.

Interesting, so would something like the below work as a route in my config.php?

Edit: code updated, and works so far for me. Note I had to use (.*) instead of (:all) to get the parameter to save for some reason.

c::set('routes', array(
  array(
    'pattern' => array('(.*)'),
    'action'  => function($vistedPage) {

      // home page check
        if($visitedPage == '/')
            $visitedPage = 'home';
      
      // if have a query, get search results here 
      
      // then...

      // activate page so intendedTemplate works
      // from https://forum.getkirby.com/t/default-fallback-in-route/4114/4?u=lukehatfield
      site()->visit($visitedPage);

      return array(
        $visitedPage,
        array(
          'query'   => $query,
          'results' => $results
        )
      );
    }
  )
));

Thanks !

I know it’s an old topic but I want to point out in case someone asking : It’s still the same trick to do for Kirby 3.
Work also to return a variable.

Shared controller :

<?php
$var = "Hello World";

Controller :

<?php
return function ($site, $page) {
  require_once kirby()->roots()->controllers() . '/shared/my-shared-controller.php';
  …
  …
  …
}

return [
  'var' => $var,
];