Base structures for Slim 4 Framework

Maintainers

Package info

bitbucket.org/magmasoftwareengineering/slim-base

Issues

pkg:composer/magmasoftwareengineering/slim-base

Statistics

Installs: 0

Dependents: 1

Suggesters: 0


README

Version: 3.x | PHP: >=8.3 | License: MIT

Overview

The Slim Base Library (magmasoftwareengineering/slim-base) provides Slim 4 framework integration and utilities built upon Doctrine Base and Base libraries. It includes abstract controllers, module settings management, and utilities for rapid development of HTTP APIs and web applications.

This is the top-level library in the Magma Software Engineering slim library hierarchy, combining all lower-level capabilities to provide a complete web application development solution. At this point, especially when coupled with magmasoftwareengineering/slim-module-middleware (providing self-contained Slim code folders (modules) Slim module loading), you have all you need to turn Slim 4 into an enterprise-capable application framework.

Key Features

HTTP Controllers

  • AbstractController - Base controller class with Slim 4 integration
  • Request/Response handling
  • Dependency injection support
  • Module settings access

Configuration Management

  • ModuleSettingsTrait / ModuleSettingsInterface - Access application settings
  • Integration with Doctrine settings entity
  • Per-module configuration

Utilities

  • Utility - Helper methods for common HTTP operations
  • Response formatting
  • Error handling

Integrated Frameworks

FrameworkPurpose
Slim 4Lightweight HTTP framework & routing
PHP-DIDependency Injection Container
Doctrine ORMDatabase entity management
TwigTemplate engine
PHP ViewNative PHP templates
Flash MessagesSession-based user feedback

Dependencies

magmasoftwareengineering/doctrine-base: ^3.0   (ORM & persistence)
php-di/slim-bridge: ^3.4                       (DI Container) 
slim/slim: ^4.15                               (HTTP framework)
slim/extras: ^2.0                              (Additional middleware)
slim/flash: ^0.4                               (Flash messages)
slim/php-view: ^3.4                            (PHP template renderer)
slim/twig-view: ^3.4                           (Twig template support)
ext-json: *                                    (JSON functions)

Transitively includes:

magmasoftwareengineering/base: ^3.0            (Logging, utilities, DI)

Installation

composer require magmasoftwareengineering/slim-base:^3.0

This automatically includes:

  • magmasoftwareengineering/doctrine-base:^3.0
  • magmasoftwareengineering/base:^3.0

Usage Examples

Creating a Controller

<?php

declare(strict_types=1);

namespace MyApp\Controller;

use MagmaSoftwareEngineering\Slim\Controller\AbstractController;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class UserController extends AbstractController {
    public function list(Request $request, Response $response): Response {
        $users = $this->entityManager->getRepository(User::class)->findAll();
        return $this->jsonResponse($response, ['users' => $users]);
    }

    public function show(Request $request, Response $response, array $args): Response {
        $user = $this->entityManager->find(User::class, $args['id']);
        if (!$user) {
            return $this->notFoundResponse($response);
        }
        return $this->jsonResponse($response, $user);
    }

    public function create(Request $request, Response $response): Response {
        $data = $request->getParsedBody();
        $user = new User();
        $user->setEmail($data['email']);
        $user->setName($data['name']);

        $this->entityManager->persist($user);
        $this->entityManager->flush();

        return $this->jsonResponse($response, $user, 201);
    }
}

Registering Routes

<?php

declare(strict_types=1);

// In your Slim application bootstrap
use Slim\Factory\AppFactory;
use MyApp\Controller\UserController;

AppFactory::determineContainerClass();
$app = AppFactory::create();

$app->group('/api/users', function ($group) {
    $group->get('', [UserController::class, ':list']);
    $group->post('', [UserController::class, ':create']);
    $group->get('/{id}', [UserController::class, ':show']);
    $group->put('/{id}', [UserController::class, ':update']);
    $group->delete('/{id}', [UserController::class, ':delete']);
});

$app->run();

Using Module Settings

<?php

declare(strict_types=1);

namespace MyApp\Controller;

use MagmaSoftwareEngineering\Slim\Controller\AbstractController;
use MagmaSoftwareEngineering\Slim\Interfaces\ModuleSettingsInterface;
use MagmaSoftwareEngineering\Slim\Traits\ModuleSettingsTrait;

class SettingsController extends AbstractController implements ModuleSettingsInterface {
    use ModuleSettingsTrait;

    public function show(Request $request, Response $response): Response {
        $appName = $this->getModuleSetting('app.name');
        $debug = $this->getModuleSetting('app.debug');

        return $this->jsonResponse($response, [
            'name' => $appName,
            'debug' => $debug,
        ]);
    }
}

Full Application Structure

my-slim-app/
├── src/
│   ├── Controller/
│   │   ├── UserController.php
│   │   └── SettingsController.php
│   ├── Entity/
│   │   └── User.php
│   ├── Repository/
│   │   └── UserRepository.php
│   └── Service/
│       └── UserService.php
├── templates/
│   └── user/
│       └── list.twig
├── config/
│   └── routes.php
├── var/
│   └── migrations/
├── public/
│   └── index.php
└── composer.json

Complete Dependency Chain

┌─────────────────────────────────────────────────────────────┐
│                    Slim Base Library                        │
│         (HTTP Controllers, Module Settings)                 │
└────────────────────────┬────────────────────────────────────┘
                         │
┌────────────────────────▼────────────────────────────────────┐
│              Doctrine Base Library                          │
│    (ORM Entities, Repositories, Transformers)               │
└────────────────────────┬────────────────────────────────────┘
                         │
┌────────────────────────▼────────────────────────────────────┐
│                  Base Library                               │
│   (Logging, JSON Parsing, CLI Commands, Utilities)          │
└─────────────────────────────────────────────────────────────┘

Related Libraries

LibraryVersionPurposeDependencies
Base Library^3.0Core utilities, logging, DIFoundation only
Doctrine Base Library^3.0ORM entities, repositoriesBuilds on Base for Doctrine/DB
Slim Base Library^3.0HTTP framework integrationBuilds on Doctrine Base

Use Cases

1. RESTful API

Use all three libraries for a complete API stack:

// Full ORM + HTTP framework + utilities
User Entity → UserRepository → UserService → UserController → HTTP Response

2. Traditional Web Application

Same stack with templates:

// Add Twig templating on top of the HTTP framework
User Entity → UserService → UserController → Twig Template → HTML Response

3. CLI Batch Processing

Use just Base Library:

// Abstract commands for background jobs
AbstractCommand → Logger → Predis (caching)

4. Microservice

Use Base + Doctrine Base:

// Entity management without full HTTP framework
Entity → Repository → Service → External HTTP client

Architecture Patterns

Controller → Service → Repository Pattern

<?php

declare(strict_types=1);

// Controller (HTTP entry point)
function create(Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $user = $this->userService->createUser($data['email'], $data['name']);
    return $this->jsonResponse($response, $user, 201);
}

// Service (Business logic)
class UserService {
    public function createUser(string $email, string $name): User {
        $user = new User();
        $user->setEmail($email);
        $user->setName($name);
        $this->repository->save($user);
        return $user;
    }
}

// Repository (Data access)
class UserRepository extends AbstractRepository {
    public function save(User $user): void {
        $this->em->persist($user);
        $this->em->flush();
    }
}

Next Steps

  • Getting Started? → Follow the examples above and refer to Base Library docs
  • Need Database Help? → Check Doctrine Base Library documentation
  • See Full Example? → Check the documentation above, if you know Slim 4 already, this is a relatively easy evolutionary path.

Support & Contributing

For issues or contributions, please contact the maintainer:

  • Jeremy Coates - hello@phpcodemonkey.me.uk

License

MIT License - See LICENSE file for details