Skip to main content
Version: Fegg 5.x

Controller

About Controller​

What is a Controller?​

A controller is the class that handles a request. Fegg picks the controller class and its method from the URL (see URL).

https://example.com/foo/bar/

For this URL, Fegg loads htdocs/_fegg/site/src/Controller/Foo.php and calls its bar() method:

htdocs/_fegg/site/src/Controller/Foo.php
<?php
namespace Site\Controller;

defined('FEGG_CORE_DIR') || exit;

class Foo extends Controller
{
public function bar()
{
// process here...
}
}

File, namespace and class​

Every controller file follows the same rules:

  • The file is in htdocs/_fegg/site/src/Controller/, and the file name is the class name (Foo.php declares class Foo).
  • The namespace is Site\Controller. Sub directories are namespaces: site/src/Controller/Cms/News.php declares namespace Site\Controller\Cms; and class News.
  • The first line after the namespace is defined('FEGG_CORE_DIR') || exit;. It is required in every PHP file under htdocs/_fegg/: it stops the file from running when someone requests it directly by URL.
  • The class extends Controller, the project's base class.
htdocs/_fegg/site/src/Controller/Cms/News.php
<?php
namespace Site\Controller\Cms;

defined('FEGG_CORE_DIR') || exit;

use Fegg\Cms\Helper;
use Fegg\Model;
use Site\Controller\Controller; // the base class is in the parent namespace

class News extends Controller
{
// ...
}

Base classes​

There are two kinds of controllers, with a base class each: public pages and CMS screens.

Fegg\Application core/src/Application.php
└ Fegg\Controller\Controller (abstract) core/src/Controller/Controller.php
├ Site\Controller\Controller (abstract) site/src/Controller/Controller.php public pages
│ └ Site\Controller\Index, News, Contact, ...
└ Fegg\Controller\Cms\Controller (abstract) core/src/Controller/Cms/Controller.php CMS screens (core)
├ Fegg\Controller\Cms\Image, Media, Login, ...
└ Site\Controller\Cms\Controller (abstract) site/src/Controller/Cms/Controller.php CMS screens (project)
└ Site\Controller\Cms\News, Lab, ...
  • Fegg\Application provides the methods you call with $this->...: request parameters, templates (displayPage(), ...), redirect(), loadConfig(), ...
  • Fegg\Controller\Controller (core) loads site/config/category_info.php and site/config/site_info.php in its __init(), and declares the properties $_model and $_lh used by the CMS.
  • Site\Controller\Controller (site) is yours: the base of the public pages. Put what every public page needs here (shared assigns, ...).
  • Fegg\Controller\Cms\Controller (core) and Site\Controller\Cms\Controller (site) are the bases of the CMS screens: see CMS screens. Put what every CMS screen of the project needs in Site\Controller\Cms\Controller.
htdocs/_fegg/site/src/Controller/Controller.php
<?php
namespace Site\Controller;

defined('FEGG_CORE_DIR') || exit;

abstract class Controller extends \Fegg\Controller\Controller
{
public function __init()
{
parent::__init();

// Shared by every page of the site
$this->page['year'] = date('Y');
}
}

Which methods are actions​

Only a controller's own actions can be called from a URL. A method is an action when it is:

  • public and not static,
  • declared in the controller itself (or a parent that is not one of the base classes above). Methods declared in Fegg\Controller\Controller, Site\Controller\Controller and the two CMS base classes are never actions, even when a controller overrides them,
  • not named like a method of Fegg\Application: mail, in, redirect, halt, setSession, setCookie, displayPage ... are 404 as URL segments,
  • not starting with _ (__init(), _validatePostedData()).

Anything else answers 404. Put shared helpers in a base class as protected methods, and write an action used by several controllers in each of them (it can call a shared helper).

Constructor​

A constructor is optional. If you write one, call the parent constructor: it loads the settings, sets up error handling and the language.

public function __construct()
{
parent::__construct();
}

Initialize​

__init() is called after the constructor, before the method of the URL. Use $this->... (for example $this->in()) here, not in the constructor.

Always call parent::__init() first. Otherwise site_info.php and category_info.php are not loaded.

public function __init()
{
parent::__init();

$this->_lh = new Helper();
$this->_model = new Model(false, array(
'table' => 'cms_news',
'id' => 'news_id',
'visible' => 'visible',
));
}
note

You can omit __init() when the controller does not need it. The parent __init() is then called automatically.

Method​

The second segment of the URL names the method; when it is empty, index() is called (see URL). A segment that names no action (see Which methods are actions) shows the 404 page.

Arguments​

The segments after the method are passed to the method as strings.

// $param1 is "bar" and $param2 is "baz"
// for https://example.com/foo/show/bar/baz/
public function show($param1 = '', $param2 = '')
{
echo $param1; // bar
echo $param2; // baz
}

Give the arguments a default value: a visitor can always open the URL with fewer segments, and a missing required argument is an error (HTTP 500).

Ending a response​

displayPage(), redirect(), requirePost(), Basic authentication and the CMS login check end the response by throwing Fegg\Http\Halt. The dispatcher catches it, writes the session and sends the output. Code after them does not run.

To stop a controller yourself, call $this->halt() instead of exit. It prints its argument, if any, and ends the response the same way:

public function ping()
{
header('Content-Type: text/plain; charset=utf-8');
$this->halt('pong'); // not: echo 'pong'; exit;
}

exit skips writing the session and sending the buffered output; halt() does both, and the code stays testable.

Halt extends \Error, not \Exception, so catch (\Exception $e) does not stop a redirect. A catch (\Throwable $e) around displayPage() or redirect() would catch it: rethrow it first.

try {
$this->_import($file);
$this->redirect('/cms/import/done/');
} catch (\Fegg\Http\Halt $halt) {
throw $halt; // the redirect: let it through
} catch (\Throwable $e) {
\Fegg\Log::error('Import failed', array('exception' => $e));
$this->displayPage('cms/import/error');
}

Using other classes​

Classes are autoloaded. Import them with use, or write the full name with a leading \, and create them with new:

use Fegg\Cms\Helper;
use Fegg\Model;
use Fegg\Tool\Validation;

$this->_lh = new Helper('news');
$validation = new Validation();
$upload = new \Fegg\Tool\Upload();
$cart = new \Site\Shop\Cart(); // htdocs/_fegg/site/src/Shop/Cart.php

Inside a namespace, prefix PHP's own classes and constants with \. Without it, PHP looks for the class in the current namespace (Site\Controller\Exception) and fails.

throw new \Exception('Something went wrong');
$date = new \DateTime('now');
$statement->bindValue(1, $id, \PDO::PARAM_INT);

Catch Fegg's exceptions by their full name, for example \Fegg\Database\QueryException or \Fegg\Template\TemplateException.

Dates and time zone​

Work with dates with PHP's DateTimeImmutable and print them with the template modifier feggDate.

$deadline = (new \DateTimeImmutable('2026-04-01 10:00:00'))->modify('+7 day')->format('Y-m-d H:i:s');
$lastDay = (new \DateTimeImmutable('2026-02-10'))->format('t'); // "28"
$days = (new \DateTimeImmutable('2026-04-01'))->diff(new \DateTimeImmutable('2026-04-10'))->days; // 9

The time zone of the application is set once at startup, from $settings['timezone'] in site/config/settings.php (default FEGG_DEFAULT_TIMEZONE, Asia/Tokyo). date(), DateTimeImmutable and feggDate all use it, and no Fegg method changes it afterwards:

  • $this->getDatetime($format = 'Y-m-d H:i:s', $timeZone = '') and $this->convertDatetime($date, $fromTimezone, $toTimezone) work on their own DateTime objects.
  • convertDatetime() returns '' for a date it cannot read.
Controller
echo $this->getDatetime('Y-m-d H:i', 'UTC'); // now, in UTC
echo $this->convertDatetime('2026-04-01 09:00:00', 'Asia/Tokyo', 'Europe/London'); // 2026-04-01 01:00:00
echo $this->convertDatetime('not a date', 'Asia/Tokyo', 'UTC'); // ''

CMS screens​

A CMS screen extends Site\Controller\Cms\Controller, which checks the login and the CSRF token of every POST; every action that changes data calls $this->requirePost() first. See CMS controllers, which also covers changing the core's CMS screens.

Template of Controller class​

htdocs/_fegg/site/src/Controller/Index.php
<?php
namespace Site\Controller;

defined('FEGG_CORE_DIR') || exit;

use Fegg\Cms\Helper;
use Fegg\Model;

class Index extends Controller
{
public function __init()
{
parent::__init();

$this->_lh = new Helper();
$this->_model = new Model(false, array(
'table' => 'cms_news',
'id' => 'news_id',
'visible' => 'visible',
));
}

// Not an action: private, and the name starts with _
private function _common()
{
}

// https://example.com/
public function index()
{
$this->_common();

$this->page['news'] = $this->_model
->order('post_date', 'desc')
->limit(5)
->all();

$this->displayPage('index'); // site/template/main/tpl/index.tpl
}
}