NAME
Minima::Controller - Base class for controllers used with Minima
SYNOPSIS
use Minima::Controller;
my $controller = Minima::Controller->new(
app => $app, # Minima::App
route => $match, # a match returned by Minima::Router
);
# Access route parameters (from URI captures)
my $post_id = $controller->route->{post};
# Access request parameters (query string or POST)
my $q = $controller->params->get('q');
# Render a response
$controller->render(
Minima::View::PlainText->new,
"Post: $post_id, search: $q\n"
);
DESCRIPTION
Serving as a base class to controllers used with Minima, this class provides the basic infrastructure for any type of controller. It is built around Plack::Request and Plack::Response objects, allowing subclasses to interactly directly with Plack.
Minima::Controller also keeps references to the Minima::App and Plack environment. Additionally, it retains data received from the router, making it readily available to controllers.
Controllers may also define optional lifecycle hooks: before_action
(to run checks before an action is executed) and after_action
(to run logic after an action has completed). For details on how these hooks are invoked during dispatch, see the run
method in Minima::App.
This base class is not connected to any view, which is left to methods or subclasses. However, it sets a default Content-Type
header for the response as 'text/plain; charset=utf-8'
and response code to 200.
CONFIGURATION
The request_encoding
key can be included in the main Minima::App configuration hash to specify the expected request encoding. The GET and POST parameters will be decoded based on this setting.
If not set, request_encoding
defaults to UTF-8
. You may use any encoding value supported by Encode.
METHODS
new
method new (app, route = {})
Instantiates a controller with the given $app
reference, and optionally the hash reference returned by the router. If this hash reference contains data extracted from the URI by Minima::Router, then this data will be made available to the controller through the route
field.
before_action
method before_action ($method)
Optional hook that runs before the action method is invoked. It receives the name of the action that is about to be executed.
If it returns a response, that response is immediately returned to the client and the action itself will not run. If it returns nothing, the normal action flow continues.
This is typically used for authentication, access control, or other pre-conditions.
See also: "run" in Minima::App.
after_action
method after_action ($response)
Optional hook that runs after the action has completed. It receives the response object returned by the action.
The return value of after_action
is ignored; any changes must be made directly to the response object. This is typically used for logging, instrumentation, or post-processing.
See also: "run" in Minima::App.
json_body
method json_body
Attempts to decode the request body as JSON. This method is useful for controllers handling application/json
POST requests.
If the Content-Type
is not application/json
, the body is empty, the declared Content-Length
is invalid, or the JSON cannot be parsed, the method returns undef
. Otherwise, it returns the decoded Perl structure (typically a hash or array reference).
redirect
method redirect ($url, $code = 302)
Utility method to set the redirect header to the given URL and code (defaults to 302, a temporary redirect) and finalize the response.
Use with return
inside other controller methods to shortcut:
# someone shouldn't be here
return $self->redirect('/login');
# continue for logged in users
render
method render ($view, $data = {})
Utility method to call render
on the passed view, together with optional data, and save to the response body. It then calls prepare_response
on the passed view and returns the finalized response.
trimmed_params
method trimmed_params ($options = {})
Returns a new Hash::MultiValue with decoded request parameters where leading and trailing whitespace in values has been removed. Keys are left unchanged. The original params
are not modified. Array values are also trimmed element-wise.
Options:
exclude
-
Array reference of parameter names (strings) or regular expressions to exclude from trimming. For example:
my $params = $self->trimmed_params( { exclude => [ 'password', qr/^raw_/ ] } );
EXTRAS
hello, not_found
Methods used to emit a minimal hello, world
or not found response.
print_env
Returns a plain text printout of the current Plack environment.
dd
method dd ($ref)
Sets the response to text/plain
, dumps the passed reference with Data::Dumper, and finalizes the response. Useful for debugging.
return dd($my_data);
ATTRIBUTES
All attributes below are accessible through reader methods.
env
-
Plack environment.
app
-
Reference to a Minima::App.
route
-
The
route
attribute contains the hash reference returned by Minima::Router. In addition tocontroller
andaction
, it may include named captures extracted from the URI pattern.For example, given this route:
GET /blog/{post} :Main show_post
The action method can access the captured parameter directly:
method show_post { my $id = $self->route->{post}; ... }
These route parameters are separate from
params
, which holds decoded query string and POST parameters. request
-
Internal Plack::Request
response
-
Internal Plack::Response
params
-
Decoded GET and POST parameters merged in a Hash::MultiValue. See "Configuration" to set the desired encoding.
Trimming whitespace is not performed automatically. If you need trimmed parameters, call
trimmed_params
, which returns a new Hash::MultiValue with leading and trailing whitespace removed from values (keys are untouched).
SEE ALSO
Minima, Minima::App, Minima::Router, Minima::View, Plack::Request, Plack::Response, perlclass.
AUTHOR
Cesar Tessarin, <cesar@tessarin.com.br>.
Written in September 2024.