I'm trying to grasp the concept of IoC and Dependency Injection in PHP, So iv'e decided to go on and create a small framework and implement these design patterns.
i've created my own IoC class which you can find here http://ift.tt/1EXYLJy
And i feed my configs like this to the IoC container at run time
// --- Main Application
[
'name' => 'Application',
'service' => [
'type' => 'constructor',
'class' => 'Pebbles\Core\Application',
'params' => [
'router' => '*AltoRouter',
'request' => '*Request',
'IoC' => '*IoC'
],
'call' => [
[
'method' => 'setRoutes',
'args' => [$routes]
]
]
],
'lazy' => FALSE
]
And the IoC class handle the dependency injection and initiliaztion.
By doing this i got my head around what actually IoC does and why is it important.
Here is how my front controller looks like :
// read $params from config file and pass it to IoC
$container = new \Pebbles\Core\IoC($params);
$container->getService('Application')->setEnvironment('dev')->run();
And this is the my Application class :
namespace Pebbles\Core;
use Symfony\Component\HttpFoundation\Request;
class Application
{
protected $request;
protected $router;
protected $container;
protected $environment;
public function __construct(\AltoRouter $router, Request $request, IoC $container)
{
$this->request = $request;
$this->router = $router;
$this->container = $container;
}
public function setEnvironment($env)
{
$this->environment = $env;
return $this;
}
public function run()
{
$match = $this->router->match();
if ($match) {
list ($controller, $action) = explode(':', $match['target']);
$object = & $this->container->getService($controller);
try {
call_user_func_array([$object, $action], $match['params']);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
But now i'm struggeling how to move forward from this point. Do i have to create a config file for all of controllers and services i'm going to use in this project and feed them to IoC (lazy) ? I mean if i'm going to have a bookingController, i have to create a config file for that and feed it to container in order to be able to use and route request to it.
but what if i have like 20 controller and 10 services ? is it still the right approach ? i'm not sure about that bit that injected the IoC itself to Application class, but how else can i route requests if i don't have access to IoC container.
Am i making mistake in implementing IoC desgin pattern ?
Here is the github link to what my actual code looks like http://ift.tt/1K9EZrl
Aucun commentaire:
Enregistrer un commentaire