User Guides

Controllers

Controllers allow you to take much more control over a website by enabling an endless list of possibilities. This section will guide you through the basics of setting up and using a controller.


Defining a Route

Before you can use a controller, you must define a route that has a controller key defining which controller and method it will use. The controller key of a route config accepts a controller/method definition in the format controllerName/methodName.

For example, the code below defines a route named blog that is configured to use the index method in the blog controller.

blog:
  path: /blog/
  controller: blog/index

Creating a Controller

Controllers are located within the 'controllers' directory of your web directory. For our example, you will need to create a new file at controllers/blog.php, the contents of this file would like something like:

<?php

namespace Controllers;

class blog {

  public function index($request, $response, $cms)
  {

  }

}

Sending a Response

You can now perform whatever tasks you would like in the controller and then send the response back to the browser.

<?php

namespace Controllers;

class blog {

  public function index($request, $response, $cms)
  {
    // Do something here...

    // Send response
    $response->send("Example response");
  }

}

Rendering a Template

You can also render templates in your controller, then send the resulting output to the browser.

<?php

namespace Controllers;

class blog {

  public function index($request, $response, $cms)
  {
    // Render a template
    $output = $cms->template->render("foo");
    // Send response
    $response->send($output);
  }

}

Templates rendered in this way will automatically have access to the current request, response and instance of LexasCMS, just as if they had been rendered directly from the routing layer.

If you need to pass more data into the templates context, that can be done by passing an array to the second parameter of the render() method. See below:

<?php

namespace Controllers;

class blog {

  public function index($request, $response, $cms)
  {
    // Define template data
    $templateData = [
      "foo" => "bar",
      "baz" => [ "bax", "qux" ]
    ];
    // Render a template, with additional context data
    $output = $cms->template->render("foo", $templateData);
    // Send response
    $response->send($output);
  }

}

Further Reading

If your website requires the use of controllers, we also recommend that you read the following API references: