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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package controller

Jasny Controller

PHP Scrutinizer Code Quality Code Coverage Packagist Stable Version Packagist License

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 output Hello 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)

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

If the argument name is used as parameter name

All request parameters

To get all request parameters of a specific type, the following attributes are available.

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
email 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

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

PHP Build Version
Package Version
Requires php Version >=8.0.0
psr/http-message Version ^1.0
willdurand/negotiation Version ^3.1
ralouphie/mimey Version ^1.0
psr/http-server-middleware Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package jasny/controller contains the following files

Loading the files please wait ....