Skip to content
Permalink
Browse files

fix(di): Fixed an issue with instantiating multiple objects

  • Loading branch information...
iiDestiny committed Mar 1, 2019
1 parent 1c97890 commit 1325df5274810d434b18b691fa91808be9c35313
Showing with 11 additions and 19 deletions.
  1. +1 −9 Zh-README.md
  2. +9 −9 src/App.php
  3. +1 −1 src/helpers.php
@@ -18,7 +18,7 @@ composer require iidestiny/dependency-injection -vvv

## 使用

使用辅助方法「推荐」
使用辅助方法

```php
// 注册你的自定义类
@@ -31,14 +31,6 @@ composer require iidestiny/dependency-injection -vvv
di_register(Tools::class)->foo($bar)
```

原本方法

```php
use Iidestiny\DependencyInjection\App;
App::register(Tools::class)
```

## 实例

例如有时候我们自定义的 Service 服务层可能也需要依赖注入其他工具类,但是我们控制器中已经依赖注入了 Service,调用 Service 中方法的时候就不能轻易的注入其他工具类,使用这个扩展包可以轻易解决这个问题,看下面例子。
@@ -18,7 +18,7 @@ class App
*
* @var
*/
protected static $instance;
protected $instance;
/**
* Instance registered
@@ -27,15 +27,15 @@ class App
*
* @return string
*/
public static function register($instance)
public function register($instance)
{
if (!is_object($instance)) {
self::$instance = new $instance();
$this->instance = new $instance();
} else {
self::$instance = $instance;
$this->instance = $instance;
}
return new self();
return $this;
}
/**
@@ -52,8 +52,8 @@ public static function register($instance)
*/
public function __call($method, $parameters)
{
if (!method_exists(self::$instance, $method)) {
$instance = get_class(self::$instance);
if (!method_exists($this->instance, $method)) {
$instance = get_class($this->instance);
throw new InvalidArgumentException("Instance [{$instance}] does not exist for [{$method}] method");
}
@@ -72,7 +72,7 @@ public function __call($method, $parameters)
*/
public function make($method, ...$parameters)
{
$reflector = new ReflectionMethod(self::$instance, $method);
$reflector = new ReflectionMethod($this->instance, $method);
foreach ($reflector->getParameters() as $key => $parameter) {
@@ -91,6 +91,6 @@ public function make($method, ...$parameters)
}
}
return call_user_func_array([self::$instance, $method], $parameters);
return call_user_func_array([$this->instance, $method], $parameters);
}
}
@@ -10,6 +10,6 @@
*/
function di_register($instance)
{
return \Iidestiny\DependencyInjection\App::register($instance);
return (new \Iidestiny\DependencyInjection\App())->register($instance);
}
}

0 comments on commit 1325df5

Please sign in to comment.
You can’t perform that action at this time.