PHP code example of koded / container

1. Go to this page and download the library: Download koded/container library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

koded / container example snippets


use PDO;

interface PostRepository {
    public function findBySlug(string $slug);
}

interface UserRepository {
    public function findById(int $id);
}

class DatabasePostRepository implements PostRepository {
    private $pdo;
    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }
    public function findBySlug(string $slug) {
        // $this->pdo ...
    }
}

class DatabaseUserRepository implements UserRepository {
    private $pdo;
    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }
    public function findById(int $id) {
        // $this->pdo ...
    }
}

class PostService {
    private $post, $user;
    public function __construct(PostRepository $post, UserRepository $user) {
        $this->post = $post;
        $this->user = $user;
    }

    // a service method that uses the post and user repository instances
    public function findBlogPostBySlug(string $slug) {
        $post = $this->post->findBySlug($slug);
        $user = $this->user->findById($post->userId());
        // ... do something with the results, create a result data structure...
    }
}

class BlogHandler {
    public function get(ServerRequestInterface $request, PostService $service): ResponseInterface {
        $slug = slugify($request->getUri()->getPath());
        $post = $service->findBlogPostBySlug($slug);

        // some PSR-7 compatible response object
        return new ServerResponse($post);
    }
}

class BlogModule implements DIModule {
    public function configure(DIContainer $container): void {
        // bind interfaces to concrete class implementations
        $container->bind(PostRepository::class, DatabasePostRepository::class);
        $container->bind(UserRepository::class, DatabaseUserRepository::class);
        $container->bind(ServerRequestInterface::class, /*some PSR-7 server request class name*/);
        
        // share one PDO instance
        $container->singleton(PDO::class, ['sqlite:database.db']);
    }
}

// index.php

// (resolved through an HTTP router or other means)
$handler = BlogHandler::class;
$method = 'get';

// by invoking the container
$response = (new DIContainer(new BlogModule))([$handler, $method]);

// we have a `$response` object to output the content
// ex. `echo $response->getBody()->getContents();`

$container('method', ['arg1', 'arg2', ...]);