Skip to content

Commit

Permalink
fix(di): Fixed an issue with instantiating multiple objects
Browse files Browse the repository at this point in the history
  • Loading branch information
iiDestiny committed Mar 1, 2019
1 parent 1c97890 commit 1325df5
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 19 deletions.
10 changes: 1 addition & 9 deletions Zh-README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ composer require iidestiny/dependency-injection -vvv

## 使用

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

```php
// 注册你的自定义类
Expand All @@ -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 中方法的时候就不能轻易的注入其他工具类,使用这个扩展包可以轻易解决这个问题,看下面例子。
Expand Down
18 changes: 9 additions & 9 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class App
*
* @var
*/
protected static $instance;
protected $instance;

/**
* Instance registered
Expand All @@ -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;
}

/**
Expand All @@ -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");
}
Expand All @@ -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) {

Expand All @@ -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);
}
}
2 changes: 1 addition & 1 deletion src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.