A controller is a class that handles requests. Controllers live in app/Controllers and usually extend BaseController.
Create a controller
php spark make:controller Posts creates app/Controllers/Posts.php in the App\Controllers namespace.
Return a response
A method can return a string, view('posts/index', $data), a redirect, or JSON with $this->response->setJSON($data).
Passing data to a view
Pass an array: keys become variables in the view. ['title' => 'Blog'] gives $title.
BaseController
app/Controllers/BaseController.php is shared by all your controllers. Put things every controller needs there — for example, helpers to load in the $helpers property, or code in initController().
Available properties
$this->request— the incoming request (form data, files)$this->response— the response object
Sub-folders
Admin controllers can go in app/Controllers/Admin with namespace App\Controllers\Admin;. Route to them as 'Admin\Dashboard::index'.
Keep controllers short: database code belongs in models.
Example
<?php
namespace App\Controllers;
class Posts extends BaseController
{
public function index()
{
$data = [
'title' => 'Latest Posts',
'posts' => ['Learn Routing', 'Learn Views', 'Learn Models'],
];
return view('posts/index', $data);
}
}
// app/Views/posts/index.php
// <h1><?= esc($title) ?></h1>
// <ul>
// <?php foreach ($posts as $post): ?>
// <li><?= esc($post) ?></li>
// <?php endforeach ?>
// </ul>
The page shows the heading "Latest Posts" and a list of three post titles. Array keys become variables in the view.