Controllers can group related HTTP request handling logic into a class. Controllers are typically stored in the app/components directory.
Here is an example of a basic controller class. All Wiggum controllers should extend the base Controller
class included with the default Wiggum installation:
<?php
namespace app\components\helloWorld;
use \wiggum\model\Component;
use \wiggum\model\Request;
use \wiggum\model\Response;
use \wiggum\commons\template\Template;
class HelloWorld extends Controller {
/**
* (non-PHPdoc)
* @see \wiggum\model\Component::doDefault()
*/
public function doDefault(Request $request, Response $response) {
$tpl = new Template('app/components/helloWorld/tpl');
$tpl->set('title', 'Hello World!');
$response->setOutput($tpl->fetch('helloWorldPage'));
return $response;
}
}
?>
We can route to the controller action like so:
$app->router->get('/helloworld', '\app\components\helloWorld\HelloWorld');
The URI would be example.com/helloworld/
Now, when a request matches the specified route URI, the doDefault method on the HelloWorld class will be executed.
It is very important to note that we specify the full controller namespace when defining the controller route. This allows you to organize your controllers the way you prefer.
In the above example the method name is doDefault()
. The doDefault()
method is always loaded by default if the method is not defined in your route. Another way to show your “Hello World” message would be this:
example.com/helloworld/something
Your route being defined as:
$app->router->get('/helloworld', '\app\components\helloWorld\HelloWorld@something');
The second part of your route (after teh @ symbol) determines which method in the controller gets called.
Let’s try it. Add a new method to your controller:
<?php
namespace app\components\helloWorld;
use \wiggum\model\Component;
use \wiggum\model\Request;
use \wiggum\model\Response;
use \wiggum\commons\template\Template;
class HelloWorld extends Component {
/**
* (non-PHPdoc)
* @see \wiggum\model\Component::doDefault()
*/
public function doDefault(Request $request, Response $response) {
$tpl = new Template('app/components/helloWorld/tpl');
$tpl->set('title', 'Hello World!');
$response->setOutput($tpl->fetch('helloWorld'));
return $response;
}
public function comments() {
$tpl = new Template('app/components/helloWorld/tpl');
$tpl->set('title', 'Something Big!');
$response->setOutput($tpl->fetch('something'));
return $response;
}
}
?>