Skip to content

Commit

Permalink
Add di-container for controller
Browse files Browse the repository at this point in the history
  • Loading branch information
BMTmohammedtaha committed Jul 12, 2023
1 parent 845f5c0 commit cf82a83
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
42 changes: 40 additions & 2 deletions src/Callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@
*/
class Callback
{
protected $container = null;

protected bool $isUseContainer = false;

/**
* set router container for binding and injected dependencies of controller class
* @param $container
* @return void
*/
public function setContainer($container): void
{
$this->container = $container;
$this->isUseContainer = true;
}
/**
* Get the callback for the given action.
*
Expand Down Expand Up @@ -70,15 +84,39 @@ public function closure(array $action): callable
[$class, $method] = $action;

if (class_exists($class)) {
$classInstance = new $class();
if ($this->isUseContainer) {
$reflection = new \ReflectionClass($class);
$constructor = $reflection->getConstructor();
// Get the parameters of the constructor
$parameters = $constructor->getParameters();
$dependencies = [];
foreach ($parameters as $parameter) {
$parameterType = $parameter->getType();

// Check if the parameter has a type
if ($parameterType !== null) {
// Get the name of the dependency class
$dependencyClass = $parameterType->getName();

// Resolve the dependency instance from the container
$dependencyInstance = $this->container->get($dependencyClass);

// Add the dependency instance to the array
$dependencies[] = $dependencyInstance;
}
}
$classInstance = new $class($dependencies);
} else {
$classInstance = new $class();
}

if (method_exists($classInstance, $method)) {
return [$classInstance, $method];
} else {
throw new Exception("Method not found: {$class}::{$method}");
}
} else {
throw new Exception("Controller class not found: {$class}");
throw new Exception("Controller class {$class} not found");
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ public function __construct()
$this->callback = new Callback();
}

/**
* set router container for binding and injected dependencies of controller class
* @param $container
* @return void
*/
public function setContainer($container): void
{
$this->callback->setContainer($container);
}

/**
* Dispatches the server request and returns a response.
*
Expand Down

0 comments on commit cf82a83

Please sign in to comment.