How to build a PHP Dependency Injection Container

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

提交回复
热议问题