How to build a PHP Dependency Injection Container

后端 未结 4 1836
我在风中等你
我在风中等你 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:03

    The question you asked has one very important catch, which I asked about in a comment. Any time you examine the possibility of pausing forward progress in order to go back and accomplish a less than trivial re-factoring of existing classes, you have to really think about the payoff.

    You replied:

    It seems a bit complex (and very different) and more work than it's worth to implement at this point. I'm just trying to hack out something real quick and see if it gains traction.

    Remember that you have the following things to do if you want to implement an DI with an IoC container properly:

    • Implement the IoC container and registry at bootstrap
    • Modify all existing classes that have dependencies to allow setter injection, while not depending on the IoC container itself
    • Re-writing / Re-structuring of your tests as needed

    A note on the second bullet which reflects my own personal view and preference, developing with DI in mind can be hard and you want the full reward it can give. One of the biggest rewards is completely decoupled objects, you don't get the complete part of that if everything still depends on an IoC container.

    That's a lot of work, especially if you haven't been considering the pattern until now. Sure, you'll have clear benefits, such as lots of re-usable and easily testable objects when you're done. But, as with all re-factoring, nothing new would be accomplished in the context of adding or finishing new functionality and features. Is difficulty testing or tight coupling getting in the way of that? That's something you'd have to weigh.

    What I suggest you do instead is keep the pattern in mind as you write new code. Provide setter methods to inject dependencies, which can be utilized manually or through an IoC container. However, have your classes continue to create them just in time if none have been injected and avoid composition in a constructor.

    At that point you'll have a collection of classes that lend much better to inversion of control, if that's a pattern you want to pursue in the future. If it works well for you and it's something you really want to incorporate into your design decisions, you can easily re-factor to remove the JIT logic later.

    In conclusion, I'm afraid that the only thing you'll end up with if you try implementing it completely, and properly right now is a mess. You can change how you write classes now going forward, but I wouldn't go back and try to implement it across the board.

    0 讨论(0)
  • 2021-02-04 09:12

    I was going to write this a comment, but it grew too long. I am not an expert so I will just give my point of view from what I've learned through few years practicing and here in SO. Feel free to use or question any part of my answer (or none).

    1.- Outside. What does the container do? The answer should be a single thing. It shouldn't have to be responsible to initialize the classes, connect to the database, handle the session and other things. Each class does one thing only.

    class ioc
      {
      public $db;
    
      // Only pass here the things that the class REALLY needs
      static public function set($var, $val)
        {
        return $this->$var = $val;
        }
    
      static function newDB($user, $pass)
        {
        return new PDO('mysql:host=localhost;dbname=test', $user, $pass);
        }
    
      static function newUser($user_id)
        {
        return new User($db, $user_id);
        }
    
      static function newLogin($session)
        {
        return new Login($this->db, $session);
        }
      }
    
    if (ioc::set('db',ioc::newDB($user, $pass)))
      {
      $user = ioc::newUser($user_id);
      $login = ioc::newLogin($session);
      }
    

    2.- You shouldn't do $friend = ioc::newUser($row['user_id']); inside your class. There you are assuming that there's a class called ioc with a method called newUser(), while each class should be able to act on it's own, not based on [possibly] other existing classes. This is called tight coupling. Basically, that's why you shouldn't use global variables either. Anything used within a class should be passed to it, not assumed in the global scope. Even if you know it's there and your code works, it makes the class not reusable for other projects and much harder to test. I will not extend myself (PUN?) but put a great video I discovered here in SO so you can dig more: The Clean Code Talks - Don't Look For Things.

    I'm not sure about how the class User behaves, but this is how I'd do it (not necessary right):

    // Allow me to change the name to Friends to avoid confusions
    class Friends
      {
      function __construct($db)
        {
        $this->db = $db;
        }
    
      function create_friends_list($user_id)
        {
        if (!empty(id))
          {
          // Protect it from injection if your $user_id MIGHT come from a $_POST or whatever
          $st = $this->$db->prepare("SELECT user_id FROM friends WHERE user_id = ?");
          $st->execute(array($user_id));
          $AllData = $st->fetchAll()
          return $AllData;
          }
        else return null;
        }
    
      // Pass the $friend object
      function get_friend_data($friend)
        {
        $FriendData = array ('Name' => $friend->get_user_name(), 'Picture' => $friend->get_profile_picture());
        return $FriendData;
        }
      }
    
    $User = ioc::newUser($user_id);
    $Friends = new Friends($db);
    
    $AllFriendsIDs = array();
    if ($AllFriendsIDs = $Friends->create_friends_list($User->get('user_id')))
      foreach ($AllFriendsIDs as $Friend)
        {
        // OPTION 1. Return the name, id and whatever in an array for the user object passed.
        $FriendData = $Friends->get_friend_data(ioc::newUser($Friend['user_id']));
        // Do anything you want with $FriendData
    
        // OPTION 2. Ditch the get_friend_data and work with it here directly. You're already in a loop.
        // Create the object (User) Friend.
        $Friend = ioc::newUser($Friend['user_id']);
        $Friend->get_user_name();
        $Friend->get_profile_picture();
        }
    

    I didn't test it, so it has probably some small bugs.

    3.- If you are learning while coding, you will have to rewrite MANY things. Try to do somethings right from the beginning so you don't need to rewrite everything, but only the classes/methods and adopting some conventions for all your code. For example, never echo from within the function/method, always return and echo from outside. I'd say that yes, it's worth it. It's bad that you have to loose 1 or 2 hours just rewriting something, but if it has to be done, do it.

    PS, sorry, I changed your bracket style everywhere.


    EDIT Reading other answers, while you shouldn't connect to the database with your ioc object, it should be perfeclty fine create a new object with it. Edited above to see what I mean.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 09:22

    Where should I instantiate my injected dependencies, such as $database, $session, etc? Would it be outside the container class, or inside the container's constructor.

    Ideally your database connection and session would be bootstrapped in. Proper DI requires an instance of a base object for which everything is registered into. So taking your IOC class as an example you need to make an instance of it ($ioc = new IOC();) then you need some kind of service provider class say

    $ioc->register('database', new DatabaseServiceProvider($host, $user, $pass))
    

    Now every time you want a connection to the database you just need to pass in $ioc->get('database'); a very rough example but I think you can see the idea is basically to store everything inside a registry and nothing is statically binded meaning you can create another instance of $ioc with totally different settings making it easy to create connections to say a different database for testing purposes.

    What if I need to create a multiple instances of the User class inside other classes? I can't inject the previously instantiated $user object because that instance is already being used. However, creating the multiple User instances inside of another class would violate the rules of DI.

    This is a common issue and there are multiple different solutions. Firstly your DI should show the difference between logged in user and just a user. You would probably want to register your logged in user but not just any user. make your user class just normal and use

    $ioc->register('login-user', User::fetch($ioc->get('database'), $user_id));
    

    so now $ioc->get('login-user') returns your logged in user. You can then use User->fetchAll($ioc->get('database')); to get all your users.

    I'm wondering if I should even adopt DI, knowing that I have to rewrite all of my previous code. I've previously been relying on global variables that I instantiate in my initialize.php, which is included in all my files.

    If you need to rewrite all your code to use DI you shouldn't probably do it. Maybe look into making a new project and work in some of your old code if you have the time. If your codebase is large I would recommend looking into breaking it down into smaller projects and using RESTFUL apis for getting and saving data. Good examples of writing APIs would be for putting your forum search into its own application /search/name?partial-name=bob would return all users with the word bob in it. you could build it up and make it better over time and use it in your main forum

    I hope you understand my answers but if you need any more info let me know.

    0 讨论(0)
提交回复
热议问题