How to build a PHP Dependency Injection Container

后端 未结 4 1838
我在风中等你
我在风中等你 2021-02-04 08:18

I\'ve recently learned about the advantages of using Dependency Injection (DI) in my PHP application. However, I\'m still unsure how to create my container for the dependencies

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 09:14

    Instead of globals in your init.php define your objects like:

    ioc::register('user', function() {
     return new User();
    });
    

    And inisde your create_friends_list method use:

    ioc::get('user')->newUser($user_id);
    

    This is a really plain implementation. Check out: http://net.tutsplus.com/tutorials/php/dependency-injection-huh/?search_index=2

    or

    http://net.tutsplus.com/tutorials/php/dependency-injection-in-php/?search_index=1

    for more information.

提交回复
热议问题