How to use DI and DI containers

I am building a small PHP mvc framework (yes, yet another one), mostly for learning purposes, and I am trying to do it the right way, so I’d like to use a DI container, but I am not asking which one to use but rather how to use one.

Without going into too much detail, the mvc is divided into modules which have controllers which render views for actions. This is how a request is processed:

  • a Main object instantiates a Request object, and a Router, and injects the Request into the Router to figure out which module was called.
  • then it instantiates the Module object and sends the Request to that
  • the Module creates a ModuleRouter and sends the Request to figure out the controller and action
  • it then creates the Controller and the ViewRenderer, and injects the ViewRenderer into the Controller (so that the controller can send data to the view)
  • the ViewRenderer needs to know which module, controller and action were called to figure out the path to the view scripts, so the Module has to figure out this and inject it to the ViewRenderer
  • the Module then calls the action method on the controller and calls the render method on the ViewRenderer

For now, I do not have any DI container set up, but what I do have are a bunch of initX() methods that create the required component if it is not already there.
For instance, the Module has the initViewRenderer() method.
These init methods get called right before that component is needed, not before, and if the component was already set it will not initialize it. This allows for the components to be switched, but it does not require manually setting them if they are not there.

Now, I’d like to do this by implementing a DI container, but still keep the manual configuration to a bare minimum, so if the directory structure and naming convention is followed, everything should work, without even touching the config.

If I use the DI container, do I then inject it into everything (the container would inject itself when creating a component), so that other components can use it?
When do I register components with the DI?
Can a component register other components with the DI during run-time?
Do I create a ‘common’ config and use that?
How do I then figure out on the fly which components I need and how they need to be set up?

If Main uses Router which uses Request,
Main then needs to use the container to get Module (or does the module need to be found and set beforehand? How?)
Module uses Router but needs to figure out the settings for the ViewRenderer and the Controller on the fly, not in advance, so my DI container can’t be setting those on the Module before the module figures out the controller and action…

What if the controller needs some other service? Do I inject the container into every controller? If I start doing that, I might just inject it into everything…

Basically I am looking for the best practices when dealing with stuff like this. I know what DI is and what DI containers do, but I am looking for guidance to using them in real life, and not some isolated examples on the net.

Sorry for the lengthy post and many thanks in advance.

EDIT: after reading a bit more, it seems that injection the container itself into objects and making them use the container to find stuff is actually service location, not dependency injection. So my latest idea is to use factories for the stuff that should be dynamically acquired based on something (like getting controllers based on what the router says), and the container would be injected into the factories where it would be used more like a service locator. The non dynamic components would be registered beforehand, and those components would be built by the container and returned fully operational, with all their dependencies filled.

So the flow would look like this:

  • get Main from the container, Main is injected with Request, Router and ModuleFactory which uses the container to find modules. This is all pre-configured
  • Main uses ModuleFactory to create the Module, injected with ModuleRouter, Request, ControllerFactory and ViewRenderer.
  • Module uses ControllerFactory to create a Controller, injected with any service that it depends on, and then the Module calls the action on the controller, and sends the result to the ViewRenderer to render the view.

Am I getting anywhere with this?

6

As there is no right or wrong in this question, I could give an example about how I like to use Dependency Injection in PHP.

I’m using the Dependency Injection Component from Symfony with the LosoDiAnnotationsBundle and extracted everything from the Bundle to use it as standalone as the Dependency Injection Component. I’m not using the rest of the Symfony Framework.

There are two functions in my system which use the Dependency Injection Container. The main function and the dispatcher. The main function (application entry point) retrieves the configured Dispatcher like this:

$dispatcher = $service_container->get('Dispatcher');
$response = $dispatcher->route( $request );

The service called “Dispatcher” is either defined in the global dependency config or annotated in the class itself like this:

 /*
 * @Service
 */
 class Dispatcher {
    /**
     * @Inject({"@service_container"})
     */
    public function __construct($serviceContainer) {
        $this->serviceContainer  = $serviceContainer;
    }
 }

The Dispatcher needs this service locator because thats how my routing works. If you use some extra mapping between routes and called methods, you could avoid this.

To inject something into other services I use the @inject annotation:

/** @Inject({"@SomeLogic", "@SomeGateway"}) */
public function setDependencies(SomeLogic $someLogic, SomeGateway $someGateway) {
    $this->someLogic = $someLogic;
    $this->someGateway = $someGateway;
}

I like this approach because the configuration of a Service Class is done in the class itself and not in a separate file. Refactoring doesn’t involve messing around with lengthy XML or YAML files.

To not harm the performance I run a script everytime I change some annotations and at build time (or in general on every vagrant up). It uses Symfony’s ContainerBuilder and PHP Dumper to generate a PHP Lookup file which extends the Base ServiceContainer Class.

The lookup for the example dispatcher would look like this:

protected function getDispatcherService()
{
    return $this->services['dispatcher'] = new SomeDispatcher($this);
}

This looks like a lot of work upfront, but it clearly separates concerns later on, especially in bigger projects. Classes do what they are supposed to do and need little to no non-domain-logic code at all.

And I try to keep factories to an absolutely minimum. The DI Container itself is one big factory and repository but it is not manually maintained.

EDIT:

My Routing Function looks like this, request_uri is something like Controller/action/...

    $path = explode( self::ACTION_SEPARATOR, $request_uri );

    if( empty( $path[1] ))
        throw new RoutingException( 'Invalid Action' );

    $method = ucfirst( $path[1] );
    $className = $path[0].'Controller';
    $qualifiedClassName = 'Some\Namespace\'.$className;

    if( !class_exists( $qualifiedClassName ))
        throw new RoutingException(sprintf('Invalid controller "%s" for route "%s"', $qualifiedClassName, $route));
    if( !is_callable( array( $qualifiedClassName, $method ) ))
        throw new RoutingException(sprintf('Invalid Action "%s"', $method));


    $controller = $this->serviceContainer->get( $className );
    call_user_func( array( $controller, $method ), $message );

5

I know its kind of a counter argument but I think it would be beneficial for you to look beyond DI.

Think about the properties of DI and what you are trying to do with applying it.

Here is a video, different aspects of programming styles are discussed(arround 25 min the case for DI is made)
http://www.infoq.com/presentations/Value-Values

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

How to use DI and DI containers

I am building a small PHP mvc framework (yes, yet another one), mostly for learning purposes, and I am trying to do it the right way, so I’d like to use a DI container, but I am not asking which one to use but rather how to use one.

Without going into too much detail, the mvc is divided into modules which have controllers which render views for actions. This is how a request is processed:

  • a Main object instantiates a Request object, and a Router, and injects the Request into the Router to figure out which module was called.
  • then it instantiates the Module object and sends the Request to that
  • the Module creates a ModuleRouter and sends the Request to figure out the controller and action
  • it then creates the Controller and the ViewRenderer, and injects the ViewRenderer into the Controller (so that the controller can send data to the view)
  • the ViewRenderer needs to know which module, controller and action were called to figure out the path to the view scripts, so the Module has to figure out this and inject it to the ViewRenderer
  • the Module then calls the action method on the controller and calls the render method on the ViewRenderer

For now, I do not have any DI container set up, but what I do have are a bunch of initX() methods that create the required component if it is not already there.
For instance, the Module has the initViewRenderer() method.
These init methods get called right before that component is needed, not before, and if the component was already set it will not initialize it. This allows for the components to be switched, but it does not require manually setting them if they are not there.

Now, I’d like to do this by implementing a DI container, but still keep the manual configuration to a bare minimum, so if the directory structure and naming convention is followed, everything should work, without even touching the config.

If I use the DI container, do I then inject it into everything (the container would inject itself when creating a component), so that other components can use it?
When do I register components with the DI?
Can a component register other components with the DI during run-time?
Do I create a ‘common’ config and use that?
How do I then figure out on the fly which components I need and how they need to be set up?

If Main uses Router which uses Request,
Main then needs to use the container to get Module (or does the module need to be found and set beforehand? How?)
Module uses Router but needs to figure out the settings for the ViewRenderer and the Controller on the fly, not in advance, so my DI container can’t be setting those on the Module before the module figures out the controller and action…

What if the controller needs some other service? Do I inject the container into every controller? If I start doing that, I might just inject it into everything…

Basically I am looking for the best practices when dealing with stuff like this. I know what DI is and what DI containers do, but I am looking for guidance to using them in real life, and not some isolated examples on the net.

Sorry for the lengthy post and many thanks in advance.

EDIT: after reading a bit more, it seems that injection the container itself into objects and making them use the container to find stuff is actually service location, not dependency injection. So my latest idea is to use factories for the stuff that should be dynamically acquired based on something (like getting controllers based on what the router says), and the container would be injected into the factories where it would be used more like a service locator. The non dynamic components would be registered beforehand, and those components would be built by the container and returned fully operational, with all their dependencies filled.

So the flow would look like this:

  • get Main from the container, Main is injected with Request, Router and ModuleFactory which uses the container to find modules. This is all pre-configured
  • Main uses ModuleFactory to create the Module, injected with ModuleRouter, Request, ControllerFactory and ViewRenderer.
  • Module uses ControllerFactory to create a Controller, injected with any service that it depends on, and then the Module calls the action on the controller, and sends the result to the ViewRenderer to render the view.

Am I getting anywhere with this?

6

As there is no right or wrong in this question, I could give an example about how I like to use Dependency Injection in PHP.

I’m using the Dependency Injection Component from Symfony with the LosoDiAnnotationsBundle and extracted everything from the Bundle to use it as standalone as the Dependency Injection Component. I’m not using the rest of the Symfony Framework.

There are two functions in my system which use the Dependency Injection Container. The main function and the dispatcher. The main function (application entry point) retrieves the configured Dispatcher like this:

$dispatcher = $service_container->get('Dispatcher');
$response = $dispatcher->route( $request );

The service called “Dispatcher” is either defined in the global dependency config or annotated in the class itself like this:

 /*
 * @Service
 */
 class Dispatcher {
    /**
     * @Inject({"@service_container"})
     */
    public function __construct($serviceContainer) {
        $this->serviceContainer  = $serviceContainer;
    }
 }

The Dispatcher needs this service locator because thats how my routing works. If you use some extra mapping between routes and called methods, you could avoid this.

To inject something into other services I use the @inject annotation:

/** @Inject({"@SomeLogic", "@SomeGateway"}) */
public function setDependencies(SomeLogic $someLogic, SomeGateway $someGateway) {
    $this->someLogic = $someLogic;
    $this->someGateway = $someGateway;
}

I like this approach because the configuration of a Service Class is done in the class itself and not in a separate file. Refactoring doesn’t involve messing around with lengthy XML or YAML files.

To not harm the performance I run a script everytime I change some annotations and at build time (or in general on every vagrant up). It uses Symfony’s ContainerBuilder and PHP Dumper to generate a PHP Lookup file which extends the Base ServiceContainer Class.

The lookup for the example dispatcher would look like this:

protected function getDispatcherService()
{
    return $this->services['dispatcher'] = new SomeDispatcher($this);
}

This looks like a lot of work upfront, but it clearly separates concerns later on, especially in bigger projects. Classes do what they are supposed to do and need little to no non-domain-logic code at all.

And I try to keep factories to an absolutely minimum. The DI Container itself is one big factory and repository but it is not manually maintained.

EDIT:

My Routing Function looks like this, request_uri is something like Controller/action/...

    $path = explode( self::ACTION_SEPARATOR, $request_uri );

    if( empty( $path[1] ))
        throw new RoutingException( 'Invalid Action' );

    $method = ucfirst( $path[1] );
    $className = $path[0].'Controller';
    $qualifiedClassName = 'Some\Namespace\'.$className;

    if( !class_exists( $qualifiedClassName ))
        throw new RoutingException(sprintf('Invalid controller "%s" for route "%s"', $qualifiedClassName, $route));
    if( !is_callable( array( $qualifiedClassName, $method ) ))
        throw new RoutingException(sprintf('Invalid Action "%s"', $method));


    $controller = $this->serviceContainer->get( $className );
    call_user_func( array( $controller, $method ), $message );

5

I know its kind of a counter argument but I think it would be beneficial for you to look beyond DI.

Think about the properties of DI and what you are trying to do with applying it.

Here is a video, different aspects of programming styles are discussed(arround 25 min the case for DI is made)
http://www.infoq.com/presentations/Value-Values

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật