Service container sample code in PHP mvc framework

Created at 27-Mar-2024 , By samar

<?php

class ServiceContainer {
    private $bindings = [];

    public function bind($name, $resolver) {
        $this->bindings[$name] = $resolver;
    }

    public function resolve($name) {
        if (isset($this->bindings[$name])) {
            $resolver = $this->bindings[$name];
            return $resolver();
        }
        throw new Exception("Service '$name' not found in the container.");
    }

}


class Request {
    public function all(){
        return array(__DIR__, __FILE__, __LINE__);
    }
}

class UserController {
    public function myFunction(Request $request) {
        print_r($request->all());
    }
}

// Instantiate the controller
$userController = new UserController();
// Get the method parameters
$methodName = 'myFunction';
$reflector = new ReflectionMethod('UserController', $methodName);
$parameters = $reflector->getParameters();

// Resolve and inject dependencies based on type hinting
$dependencies = [];

$container = new ServiceContainer();
$container->bind('Request', function(){
    return new Request();
});
foreach ($parameters as $parameter) {
    $dependencyClassName = $parameter->getType()->getName();
    $dependencies[] = $container->resolve($dependencyClassName);
}
// Call the method with the resolved dependencies
$userController->$methodName(...$dependencies);

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.