Download the PHP package jasny/controller without Composer
On this page you can find all versions of the php package jasny/controller. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download jasny/controller
More information about jasny/controller
Files in jasny/controller
Package controller
Short Description A general controller for PSR-7
License MIT
Informations about the package controller
Jasny Controller
PSR-7 controller for Slim Framework and other micro-frameworks.
The controller is responsible handling the HTTP request, manipulate the model and initiate the view.
The code in the controller read as a high level description of each action. The controller should not contain implementation details. This belongs in the model, view or in services and libraries.
Installation
Install using composer
composer require jasny\controller
Setup
Jasny\Controller
can be used as a base class for each of your controllers. It lets you interact with the
PSR-7 server request and response in a friendly matter.
Visiting
https://example.com/hello/Arnold&others=friends
would outputHello Arnold and friends
.
Actions are defined as public methods of the controller.
A controller is a callable object by implementing the __invoke
method. The invoke method takes a PSR-7
server request and response object and will return a modified response object. This all is abstracted away when you
write your controller.
A router typically handles the request and chooses the correct controller object to call. The router is also responsible for extracting parameters from the url path and possibly choosing a method to call within the controller.
Slim framework
Slim is a PHP micro-framework that works with PSR-7. To use this library with slim, use the provided middleware.
Optionally, the middleware can convert error responses from the controller to Slim HTTP Errors by passing true
to the
middleware constructor.
Relay + SwitchRoute
SwitchRoute, a super-fast router based on generating code. The router needs a PSR-15 request handler to work with PRS-7 server requests, like Relay.
By default, the route action is converted to the method that will be called by the PSR-15 handler. For this library,
__invoke
should be called instead. The invoke method will take care of calling the right method within the controller.
See SwitchRoute for more information
Output
When using PSR-7, you shouldn't use echo
, because it makes it harder to write tests. Instead, use the output
method
of the controller, which writes to the response body stream object.
A second argument may be passed, which sets the Content-Type
header. You can pass a mime type like 'text/html'.
Alternatively you can use a common file extension like 'txt'. The controller uses the
ralouphie/mimey library to get the mime type.
JSON
The json
method can be used to serialize and output data as JSON.
Response status
To set the response status you can use the status()
method. This method can take the response status as integer or
as string specifying both the status code and phrase.
Alternatively and preferably you can use helper method to set a specific response status. Some method can optionally take arguments that make sense for that status.
The following methods for setting the output status are available
status code | method | |
---|---|---|
200 | ok() |
|
201 | created(?string $location = null) |
Optionally set the Location header |
202 | accepted() |
|
204/205 | noContent(int $code = 204) |
|
206 | partialContent(int $rangeFrom, int $rangeTo, int $totalSize) |
Set the Content-Range and Content-Length header |
30x | redirect(string $url, int $code = 303) |
Url for the Location header |
303 | back() |
Redirect to the referer |
304 | notModified() |
|
40x | badRequest(int $code = 400) |
|
401 | unauthorized() |
|
402 | paymentRequired() |
|
403 | forbidden() |
|
404/405/410 | notFound(int $code = 404) |
|
406 | notAcceptable() |
|
409 | conflict() |
|
429 | tooManyRequests() |
|
5xx | error(int $code = 500) |
- Some methods take a
$message
argument. This will set the output. - If a method takes a
$code
argument, you can specify the status code. - The
back()
method will redirect to the referer, but only if the referer is from the same domain as the current url.
Sometimes it's useful to check the status code that has been set for the response. This can be done with the
getStatusCode()
method. In addition, there are methods to check the type of status.
status code | method |
---|---|
1xx | isInformational() |
2xx | isSuccessful() |
3xx | isRedirection() |
4xx | isClientError() |
5xx | isServerError() |
4xx or 5xx | isError() |
Response headers
You can set the response header using the setResponseHeader()
method.
By default, response headers are overwritten. In some cases you want to have duplicate headers. In that case set the
third argument to true
, eg header($header, $value, true)
.
Input
With PSR-7, you shouldn't use super globals $_GET
, $_POST
, $_COOKIE
, and $_SERVER
. Instead, these values are
available through the server request object. This is done using PHP attributes.
Attribute | Arguments | |
---|---|---|
PathParam |
name, type | Path parameter obtained from router |
QueryParam |
name, type | Query parameter |
Query |
All query parameters | |
BodyParam |
name, type | Body parameter |
Body |
All body parameters or raw body as string | |
Cookie |
name, type | Cookie parameter |
Cookies |
All cookies as key/value | |
UploadedFile |
name | PSR-7 uploaded file(s) |
UploadedFiles |
Associative array of all uploaded files | |
Header |
name, type | Request header (as string) |
Headers |
All headers as associative array | |
Attr |
name, type | PSR-7 request attribute set by middleware |
The controller will map each argument of a method to a parameter. By default, arguments are mapped to path parameters.
Parameters
Path parameters
A router may extract parameters from the request URL. In the following example, the url path /hello/world
,
the path parameter name
will have the value "world"
.
The name
parameter will be passed as argument to the hello
method.
Single request parameter
The controller will pass PSR-7 request parameters as arguments. This is specified by an attribute
QueryParam
BodyParam
Cookie
UploadedFile
Header
If the argument name is used as parameter name
- for
QueryParam
, underscores are replaced with dashes. Eg:$foo_bar
will translate to query paramfoo-bar
. - for
Header
, words are capitalized and underscores become dashes. Eg:$foo_bar
translates to headerFoo-Bar
.
All request parameters
To get all request parameters of a specific type, the following attributes are available.
Query
Body
Cookies
UploadedFiles
Headers
For the Body
attribute, the type of the argument should either be an array or a string. If an array is passed the
argument will be the parsed body. In case of a string it will be the raw body.
PSR-7 request attribute
Middleware can set attributes of the PSR-7 request. These request attributes are available as arguments by using the
Attr
attribute.
Parameter name
For single parameters, the name of the argument will be used as parameter name. Alternatively, it's possible to specify a name when defining the attribute.
Note: #[PathParam]
could be omitted, since it's the default behaviour.
Parameter type
It's possible to specify a type as second argument when defining the attribute. By default, the type is determined on the type of the argument.
Parameter attributes use the filter_var
function to sanitize input. The following
filters are defined
type | filter |
---|---|
bool | FILTER_VALIDATE_BOOL |
int | FILTER_VALIDATE_INT |
float | FILTER_VALIDATE_FLOAT |
FILTER_VALIDATE_EMAIL |
|
url | FILTER_VALIDATE_URL |
For other types (like string
), no filter is applied.
To add custom types, add filters to SingleParameter::$types
Content negotiation
Content negotiation allows the controller to give different output based on Accept
request headers. It can be used to
select the content type (switch between JSON and XML), the content language, encoding, and charset.
Method | Request header | Response header |
---|---|---|
negotiateContentType() |
Accept |
Content-Type |
negotiateLanguage() |
Accept-Language |
Content-Language |
negotiateEncoding() |
Accept-Encoding |
Content-Encoding |
negotiateCharset() |
Accept-Charset |
negotiateCharset()
will modify the Content-Type
header if it's already set. Otherwise, it will just
return the selected charset.
The negotiate method takes a list or priorities as argument. It sets the response header and returns the selected option.
For more information, please check the documentation of the willdurand/negotiation library.
Hooks
In addition to the action method, the controller will also call the before()
and after()
method.
Before
The before()
method is call prior to the action method. If it returns a response, the method action is never called.
Instead of before()
consider using guards.
After
The after()
method is called after the action, regardless of the action response type.
Guards
Guards are PHP Attributes that are invoked before the controller method is called. A guard is similar to middleware, though more limited. The purpose of using a guard is to check if the controller action may be executed. If the guard returns a response, that response is emitted and the method on the controller is never called.
A guard class should implement the process
method. A guard class has the same methods as a controller class. The
process
method can have input parameters.
Order of execution
Guards may be defined on the controller class or the action method. The order of execution is
- Class guards
before()
- Method guards
- Action
after()
Dependency injection
Guards are attributes, which are instantiated using PHP reflection. Parameters can be specified when the guard is declared.
This makes it difficult to make a service (like a DB connection) available to a guard using dependency injection.
Some DI container libraries, like PHP-DI, are able to inject services to an already instantiated
object. To utilize this, overwrite the Guardian
class and register it to the container.
The guard class can use #[Inject]
attributes or @Inject
annotations.
Make sure the Guardian
service is injected into the controller using dependency injection.
All versions of controller with dependencies
psr/http-message Version ^1.0
willdurand/negotiation Version ^3.1
ralouphie/mimey Version ^1.0
psr/http-server-middleware Version ^1.0