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
- Shorthand for isset() in php
- How to add php8.2 in ubuntu
- Delay code execution in PHP
- How to add elements to an empty array in PHP?
- How to remove duplicate items from an array in PHP
- How to remove duplicate values from Array in PHP
- How to display data in ckeditor?
- PHP number format indian currency
- Get the first key of an array in php
- Convert an array to string in PHP
- How to add new item to array in PHP
- How to get image tmp_name in PHP
- How to set php executable path php.validate.executablePath in vscode
- Convert comma-separated string into array in PHP
- If statement with multiple conditions in php
- User-defined functions in php
- How to displaying ckeditor save HTML data from SQL database
- Required parameter $originalDate follows optional parameter $format
- Show errors in php
- You are trying to access an array as object
- Type hinting in PHP
- How to increment variable value by 1 in php
- Convert string to sha512 in PHP
- How to check If an element exists in Array in php
- How to get date with day, month, year, weekdays from string "2021/08/12" in php