How can you implement dependency injection in Slim Framework?

How can you implement dependency injection in Slim Framework?

To implement Dependency Injection (DI) in the Slim Framework, you can use its built-in container (based on PSR-11 standard). Here’s a minimal guide to implementing DI in Slim:

Steps to Implement Dependency Injection in Slim Framework:

  1. Set Up a Dependency Container: Slim uses a PSR-11 compliant container (like PHP-DI or Pimple) to manage dependencies. You can define services in the container.

Example

<?php
use Psr\Container\ContainerInterface;
use Slim\Factory\AppFactory;

// Create App with a container
$container = new \DI\Container(); // PHP-DI container
AppFactory::setContainer($container);
$app = AppFactory::create();
?>
  1. Register Dependencies in the Container:
Add services or objects you want to inject via the container. For example, you can inject a logger service or any class.

Example

<?php
// Register a service in the container
$container->set('logger', function (ContainerInterface $c) {
    $logger = new \Monolog\Logger('app');
    $logger->pushHandler(new \Monolog\Handler\StreamHandler('path/to/logfile.log'));
    return $logger;
});
?>
  1. Use Dependency Injection in Routes:
To inject a service in a route, simply request it from the container.

Example

<?php
$app->get('/log', function ($request, $response, $args) {
    // Access the logger service from the container
    $logger = $this->get('logger');
    $logger->info('Logging info from the route');
    $response->getBody()->write("Logged successfully!");
    return $response;
});
?>
  1. Inject Dependencies into Controllers or Classes: You can also inject dependencies into custom classes (like controllers) by accessing the container in your class constructor.

Example

<?php
class MyController
{
    protected $logger;

    // Inject the logger dependency
    public function __construct(ContainerInterface $container)
    {
        $this->logger = $container->get('logger');
    }

    public function logSomething($request, $response)
    {
        $this->logger->info('Logged from controller');
        $response->getBody()->write("Logged from controller");
        return $response;
    }
}

// Add route with injected controller
$app->get('/controller-log', [MyController::class, 'logSomething']);
?>
  1. Run the Application:
After defining the container and routes, run your Slim application as usual.

Example

<?php
$app->run();
?>

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.