This paper implements set injection in the form of Java-like annotation.
First DI container code
require ' docparser.php '; class Container{ /** * Use containers to instantiate objects, external call interface * @param $name as class name eg. ' User ' * / Public function get($name) { Static $cache=Array();if(isset($cache[$name])) {return $cache[$name]; }require ' models/'. Ucfirst ($name) .'. php ';$reflection=NewReflectionclass ($name);$depends=$this->getdependency ($reflection);$cache[$name] =$this->createobject ($reflection,$depends);return $cache[$name]; }/** * Use reflection to get the dependency conditions required by the class, the comment contains the public variable for the @inject annotation * @param $reflection reflectionclass */ Public function getdependency($reflection) { $depends=Array();$props=$reflection->getproperties (Reflectionproperty::is_public);foreach($props as $prop) {$str=$prop->getdoccomment ();$parser=NewDocparser ();$anotations=$parser->parse ($str);if(isset($anotations[' inject '])) {$depends[$prop->getname ()] =$anotations[' inject ']; } }return $depends; }/** * Method of instantiating an object * @param $instance reflectionclass * @param $depends Array (' field ' = ' class '), field is the injected variable name, class is the injected classes * / Public function createobject($instance, $depends) { $instance=$instance->newinstanceargs (Array());foreach($depends as $key=$value) {$instance->{$key} =$this->get ($value); }return $instance; }}
Which DocParser.php
is the tool class for parsing PHP annotations.
- How to use this article
Create a new folder under a sibling directory models
, create a newUser.php
class User{ /** * 使用inject注解来标明该变量需要注入,后面跟着需要注入的类名 * @inject Email */ public$email; publicfunction sendEmail() { $this->email->sendEmail(); }}
NewEmail.php
class Email{ publicfunction sendEmail() { echo‘send email!‘; }}
In the root directory, create a newindex.php
require‘Container.php‘;$dinew Container();$user$di->get(‘User‘);$user->sendEmail();
Run and index.php
you can see the results.
This article only demonstrates the IOC implementation process, without considering the actual usage scenario.
Source
PHP implements IOC set injection