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.
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.
Random Code Snippet Queries: Php
- Show errors in php
- How to increment variable value by 1 in php
- How to set php executable path php.validate.executablePath in vscode
- How to check If an element exists in Array in php
- How to display data in ckeditor?
- How to check file is an image in php
- Convert comma-separated string into array in PHP
- How to remove duplicate items from an array in PHP
- How to add php8.2 in ubuntu
- Get the first key of an array in php
- User-defined functions in php
- Delay code execution in PHP
- Shorthand for isset() in php
- How to add new item to array in PHP
- Convert an array to string in PHP
- How to remove duplicate values from Array in PHP
- How to get date with day, month, year, weekdays from string "2021/08/12" in php
- Array to string conversion error in PHP
- Type hinting in PHP
- Page view counter in PHP
- Class "finfo" not found
- How to get image tmp_name in PHP
- How to add elements to an empty array in PHP?
- You are trying to access an array as object
- Required parameter $originalDate follows optional parameter $format