Interfacing between slim router and other portions of the app

What is the “proper” Slim way of communicating between the router and other portions of the application? I’ve included two examples below. Thanks

Option 1

$api->post('/users', function(Request $request, Response $response) {
    try {
        $newUser = $this->apiUserService->create($request->getParsedBody());
        return $response->write($newUser);
    } catch (PermissionDeniedError $e) {
        return $response->write($e->getMessage())->withStatus(401);
    } catch (UserValidationError $e) {
        return $response->write($e->getMessage())->withStatus(422);
    }
});
class apiUserService
{
    public function create(array $params): User
    {
        // If successful, return user else throw exception
    }
}

Option 2

$api->post('/users', function(Request $request, Response $response) {
    return $this->apiUserService->create($request->getParsedBody(), $response);
});

class apiUserService
{
    public function create(array $params, Response $response): Response
    {
        // Modify $response body and status as applicable and return $response for all conditions
    }
}

There is a “rule”. Never pass the response or the request object to the service layer. It’s only allowed to pass the request “values” as parameters but never pass the request or the response directly. Only the controller (or action) is responsible to mediate between the Controller © and the View (V). The service belongs to the Model layer (M), therefore don’t pass any controller related objects to the Model layer.

1 Like