PHPackages                             adeptoas/slim3-init - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. adeptoas/slim3-init

ActiveLibrary[Framework](/categories/framework)

adeptoas/slim3-init
===================

A very convenient support library for Slim 3

v4.1.2(2y ago)13711proprietaryPHPPHP &gt;=7.4

Since Aug 12Pushed 2y ago4 watchersCompare

[ Source](https://github.com/visma-meglerfront/slim3-init)[ Packagist](https://packagist.org/packages/adeptoas/slim3-init)[ RSS](/packages/adeptoas-slim3-init/feed)WikiDiscussions master Synced yesterday

READMEChangelog (8)Dependencies (4)Versions (39)Used By (0)

Slim3 Init
==========

[](#slim3-init)

This is a very convenient wrapper around the Slim4 framework providing us with some shortcuts and prepopulated concepts.

Installation
------------

[](#installation)

Add this to `composer.json`:

```
"require": {
	"adeptoas/slim3-init": "^4.0.0"
}
```

Make sure to merge your `require`-blocks!

Usage
-----

[](#usage)

### SlimInit

[](#sliminit)

- #### Create a SlimInit instance

    [](#create-a-sliminit-instance)

    ```
     $app = new SlimInit();
    ```
- #### Set debug header

    [](#set-debug-header)

    If this header is present in the request, it will enable additional information to be shown when using the default exception handler. Set null to disable this feature.

    ```
     setDebugHeader(?string $header, string $expectedValue = ''): SlimInit
    ```
- #### Map an exception to an HTTP status code

    [](#map-an-exception-to-an-http-status-code)

    Set the HTTP status code for an exception when using the default exception handler.

    ```
     setException(string $exception, int $statusCode): SlimInit
    ```
- #### Map an exception to an exception handler

    [](#map-an-exception-to-an-exception-handler)

    Customize the handling of an exception entirely. `$exceptionHandlerClass` must be the fully qualified name of a class that extends `Adepto\Slim3Init\Handlers\ExceptionHandler`.

    ```
     setException(string $exception, string $exceptionHandlerClass): SlimInit
    ```
- #### Map multiple exceptions to an exception handler or status code

    [](#map-multiple-exceptions-to-an-exception-handler-or-status-code)

    ```
     setException(array $exceptions, int|string $statusCodeOrHandlerClass): SlimInit
    ```
- #### Example: Add error collection services like Raygun, Sentry, …

    [](#example-add-error-collection-services-like-raygun-sentry-)

    To send an exception to an error collection service, add an exception callback:

    ```
     /** @var $app \Adepto\Slim3Init\SlimInit */
     $app->addExceptionCallback(function(\Adepto\Slim3Init\Request $request, Throwable $t) {
     	// Send $t to the service
     });
    ```

    Or as a class:

    ```
     class ExceptionCallback {
     	public function __invoke(\Adepto\Slim3Init\Request $request, Throwable $t) {
     		// Send $t to the service
     	}
     }

     /** @var $app \Adepto\Slim3Init\SlimInit */
     $app->addExceptionCallback(new ExceptionCallback());
    ```
- #### Add something to the container

    [](#add-something-to-the-container)

    ```
     addToContainer(string $key, mixed $value): SlimInit
    ```
- #### Add a single handler

    [](#add-a-single-handler)

    `$className` must be the name of a class that extends `Adepto\Slim3Init\Handlers\Handler`.

    ```
     addHandler(string $className): SlimInit
    ```
- #### Add multiple handlers from a directory

    [](#add-multiple-handlers-from-a-directory)

    Add all handlers from a specific directory. Non-recursive and the filenames must be the class names followed by `.php`.

    ```
     addHandlersFromDirectory(string $dir): SlimInit
    ```
- #### Add Slim 4-compatible middleware

    [](#add-slim-4-compatible-middleware)

    Refer to Slim's documentation for more information about middleware.

    ```
     addMiddleware(callable $middleware): SlimInit
    ```
- #### Run!

    [](#run)

    Boot up the application and listen to incoming requests. Automatically appoints all handlers and maps everything.

    ```
     run(): Slim\App
    ```

---

### HandlerCaller

[](#handlercaller)

All mocking methods return the text output that would've been sent to the browser. This is a JSON string most of the times.

- #### Create a HandlerCaller

    [](#create-a-handlercaller)

    Create a caller for `$handlerClass`. You can leave $baseURL empty but for consistency and compatibility you should set this to the base URL this handler would've listened to (without the route URL).

    ```
     $caller = new HandlerCaller(string $baseURL, string $handlerClass);
    ```
- #### GET

    [](#get)

    Mock a GET request to `$url` with `$headers`.

    ```
     get(string $url, array $headers = []): string
    ```
- #### POST

    [](#post)

    Mock a POST request to `$url` with `$headers` and send `$body` with it. If `$body` is an array, it will be converted to Form or JSON, based on `Content-Type` in `$headers` (default is Form).

    ```
     post(string $url, array $headers, mixed $body): string
    ```
- #### PUT

    [](#put)

    Mock a PUT request to `$url` with `$headers` and send `$body` and `$files` with it. If `$body` is an array, it will be converted to Form or JSON, based on `Content-Type` in `$headers` (default is Form).

    ```
     put(string $url, array $headers, mixed $body, array $files = []): string
    ```
- #### PATCH

    [](#patch)

    Same as POST, just with PATCH as HTTP method and `$files`.

    ```
     patch(string $url, array $headers, mixed $body, $files = []): string
    ```
- #### DELETE

    [](#delete)

    Same as POST, just with DELETE as HTTP method.

    ```
     delete(string $url, array $headers, mixed $body): string
    ```

---

### Handler

[](#handler)

To have your API do something, you need to create handlers which extend `Adepto\Slim3Init\Handlers\Handler`. Each handler must override `getRoutes(): array` to return an array of routes. Each handler receives a container in the constructor by default.

The actual methods of your handler must have the following signature:

```
public function someName(Adepto\Slim3Init\Request $request, Adepto\Slim3Init\Response $response, \stdClass $args): Adepto\Slim3Init\Response
```

---

### PrivilegedHandler

[](#privilegedhandler)

Same as for Handler, only that this type of handler also has to override `actionAllowed(string $action, array $data = []): bool` to determine, if a given action is allowed and permitted. A PrivilegedHandler has an authorization client (client used to authenticate, instance of `Adepto\Slim3Init\Client\Client`) via `getClient()`.

```
forcePermission(string $action, array $data = []): bool
```

Force a permission. This is basically just an alias for `actionAllowed` (which you have to override) but throws a `Adepto\Slim3Init\Exceptions\AccessDeniedException` if the given permission is not allowed.

---

### Route

[](#route)

Defines a route which has to be returned inside an array returned by your handler's `getRoutes()` function.

```
new Route(string $httpMethod, string $url, string $classMethod, array $arguments = [], string $name = '')
```

- `$httpMethod`: The HTTP verb used for this route, i.e. GET, POST, PATCH, ...
- `$url`: Slim-compatible URL pattern, i.e. `/client/{client:[a-zA-Z0-9]+}`
- `$classMethod`: The name of the method to be called in the handler.
- `$arguments`: Additional arguments to add to `$args` of the method.
- `$name`: Name for the route so that it can be retrieved by any handlers.

---

### Interface: Client

[](#interface-client)

- ```
     getUsername(): string
    ```

    Should return the username of the currently logged in user (if `BasicAuth` was used).
- ```
     getPermissions(): array
    ```

    Should return an array full of `Adepto\Slim3Init\Client\Permission` objects for the currently logged in user ( if `BasicAuth` was used).
- ```
     hasPermission(string $name, array $data = []): bool;
    ```

    Should return true when the currently logged in user has a certain permission. You can use `$data` to combine the permission with more info, i.e. when a resource's information access should be constrained to certain IDs.

---

### Interface: Permission

[](#interface-permission)

- ```
     getName(): string
    ```

    Should return the name of the permission. You are free to define how a name looks like. It is recommended to use reverse-domain style, i.e. `adepto.api.addKnowledge`.
- ```
     getData(): array
    ```

    Should return information specific to that permission, i.e. IDs of a resource that can be accessed. Can be an empty array, if there is no information.
- ```
     isAllowed(): bool
    ```

    Should return true, if the permission is allowed.

---

### Abstract: BasicAuth (Middleware)

[](#abstract-basicauth-middleware)

- ```
     authorize(array $credentials): array
    ```

    Should return an array with more information to be added to the container, i.e. an authorized client to be used with a PrivilegedHandler. If you're going to return a client, make sure to set the key to `PrivilegedHandler::CONTAINER_CLIENT`. Should throw an `Adepto\Slim3Init\Exceptions\UnauthorizedException` if the user could not be authorized.

---

Examples
--------

[](#examples)

Examples can be found in `examples/` of this repository.

---

Upgrade from SlimInit 1.0 (using Slim3)
=======================================

[](#upgrade-from-sliminit-10-using-slim3)

While quite a lot has changed under the hood in Slim, the actual effects on SlimInit are as minimal as possible. There are 3 breaking changes and a few minor changes.

Breaking Changes
----------------

[](#breaking-changes)

### 1. Handlers now must return an instance of `Adepto\Slim3Init\Response`

[](#1-handlers-now-must-return-an-instance-of-adeptoslim3initresponse)

Previously, all handlers were defined using only Psr7-compatible interfaces. While you can still define your handler's arguments using Psr7, the return value must definitely be an instance of `Adepto\Slim3Init\Response`. If you need to convert an existing response, use `Response::fromSlimResponse($originalResponse)`.

### 2. Middleware handling changes from a callback `$next()` to a handler

[](#2-middleware-handling-changes-from-a-callback-next-to-a-handler)

This change comes directly from Slim4, as SlimInit does not change this behavior. Previously, middleware worked like this:

```
