Controllers

Controllers are template-specific classes. Their main responsibilities include processing user input, fetching data from the Model (ProcessWire), formatting it as needed, and passing it to the View.

Controllers should contain any business logic related to the template – or, at least, business logic that doesn't belong to a separate module or class. One of the key concepts of MVC is separation of concerns, and the first step towards that goal is not mixing business logic with markup generation.

Controllers are optional

Note that Controllers are also completely optional: if a Page can be rendered without complex business rules, meaning that you just need some basic control structures, loops, and echo/print statements, it is perfectly fine to leave Controllers out of the equation and request data directly from ProcessWire's API.

For an example: it's OK to echo content from a page field or iterate over page's children in the view script, but if you're building a search query based on user input, the code used for this purpose definitely belongs into a Controller.

When a Page is rendered, Wireframe will check if it can find and instantiate a template-specific Controller class. If it can't, it'll just continue rendering the Page without one.

Files and class names

First things first: in Wireframe a Controller is tied to a single template, and should contain a class (and one class only) named after the template. Controller files need to be placed into the controllers directory under /site/templates/, and the syntax for Controller class names is [TemplateNameInCamelCase]Controller.

For an example the Controller class for the "home" template would be HomeController, and this class should be placed in /site/templates/controllers/HomeController.php. If the template was "basic-page", Controller class would be BasicPageController, and the filename would be /site/templates/controllers/BasicPageController.php.

Creating a Controller

Here's a very simple Controller implementation for the "home" template (/site/templates/controllers/HomeController.php):

<?php
  
namespace Wireframe\Controller;
  
class HomeController extends \Wireframe\Controller {
  
    /**
     * Init method gets executed automatically
     */
    public function init() {
        $view->some_var = "some value";
    }
  
    /**
     * Another method. Controller methods can be accessed as parameters from
     * within Layout files and View Scripts.
     *
     * @return string
     */
    public function someOtherVar() {
        return "some other value";
    }
  
}

Here are some key points to keep in mind when working with Controllers:

Back to top