๐งญ Controllers
Controllers in Cardikit are responsible for handling incoming HTTP requests and returning appropriate responses. They serve as the bridge between routes and business logic.
Each controller method corresponds to a specific action and is usually tied to a route in the router.
๐ ๏ธ How Controllers Work
Routes are mapped to controller methods using:
Router::post('/login', [AuthController::class, 'login']);
This calls the login()
method on the AuthController
class when a POST request is made to /login
.
See ๐งญ routing for more information about defining routes.
๐งช Example: AuthController
Located at: App\Controllers\AuthController.php
๐นregister(Request $request): void
Registers a new user after validating input.
- Uses the Validator to enforce rules on:
name
: required, string, 2-10 charactersemail
: required, email format, must be uniquepassword
: required, string, at least 8 characters, confirmed
- Saves the user to the database.
- Returns response.
Response:
201 Created
on success422 Unprocessable Entity
on validation error
๐นlogin(Request $request): void
Authenticates an existing user.
- Uses the Validator to enforce rules on:
email
: required, email formatpassword
: required, string
- Verifies credentials with
password_verify()
. - Sets session variables on success.
- Returns response.
Response:
200 OK
on success401 Unauthorized
on authentication failure422 Unprocessable Entity
on validation error
๐นlogout(): void
Destroys the session and removes session cookies.
- Clears
$_SESSION
and cookie viasession_destroy()
. - Returns response.
Response:
200 OK
on success
๐นcsrfToken(): void
Generates a new CSRF token.
- Saves token to
$_SESSION['csrf_token']
- Returns token in JSON
Response:
{
"csrf_token": "generated_token_here"
}
โจ Writing Your Own Controllers
- Create a class in
App\Controllers
- Add public methods to handle specific routes
- Accept
Request $request
if needed for body or params - Return output using the
Response
helper
Example:
class PingController
{
public function pong(Request $request): void
{
Response::json(['message' => 'pong']);
}
}