Skip to content

3.1 Modules | controller.php

GrumpyCrouton edited this page Oct 12, 2022 · 11 revisions

Create a Controller

A controller is the brain of your module. It tells the server what view to render, and tells models what to do.

Inside of the module folder, create a file called controller.php. Make sure to change the namespace to match the folder name of the module.

controller.php:

<?php
namespace modules\home;
class controller extends \Controller {

	public function get() {
                //load/interact with models
                //set variables usable view
                //load view
		die('hello world');
	}

}

This is the most basic form of a controller. If I accessed this controller with the url example.com/home, I would get a message on a plain white background that says "hello world".

Notice the method I used is get(). This is because GF3 runs a module controller method based on the HTTP Method that was used to access the page.

You can also specify a method to run via the URL. For example, I could add another method called another_page(), and access it with the url example.com/home/another_page

Controller properties

There are few properties and methods a controller allows you to access. Generally, you access these by using $this->{property or method}.

  • f3 - Access BASE methods
  • settings - Access contents of settings.json in module root
  • reroute() - Matches F3's reroute method, pass SELF::REROUTE_MODULE as 2nd param to redirect with the module as the base path

When a module is loaded, it stores a reference to itself in a global variable called active_module (accessible via $f3->get('active_module')).

Handling POST submissions

Since GF3 runs a method based on the HTTP Method used, if you render a form through a get() method, the resulting POST request will be sent to a post() method.

If you are submitting a form from a custom method, such as another_page() from the example above, you will have to explicitly check if the user has just submitted a form like below.

public function another_page() {
        //load/interact with models
	if($this->f3->VERB == "POST") {
                //load/interact with models
		//handle POST request
		die();
	}
        //set variables usable view
        //load view
}