簡體   English   中英

我如何最好地在另一個使用Pimple進行依賴注入的類中使用對象工廠?

[英]How do I best use an object factory inside another class using Pimple for Dependency Injection?

我仍在嘗試使用Pimple圍繞“依賴注入”設計模式的某些方面。 我完全理解了使用屬於Foo類的構造函數或setter函數來建立其對Bar類的依賴的概念。

我不太了解的部分是如何在使用Pimple工廠時從屬於Foo的方法內部正確實例化Bar類的多個新實例。

基本上,我想完成以下工作:

Block.php

class Block {

     private $filepath;

     public function setFilePath($filepath) {
          $this->filepath = $filepath;
     }

}

Page.php

class Page {

     private function newBlock() {
          //do something here to get $filepath
          $block = new Block();
          $block->setFilePath($filepath);
          return $block;
     }

}

我正在為容器使用Pimple,如下所示:

bootstrap.php

$container = new Container();

$container['page'] = $container->factory(function ($c) {
    return new Page();
});

$container['block'] = $container->factory(function ($c) {
     return new Block();
});

這個想法是可以定義多個頁面,每個頁面可能由多個塊組成。 每個塊的屬性由Page中的方法定義。 它需要使用完全解耦的代碼來實現。

據我了解,將整個容器作為依賴項注入到Page中實際上是Service Locator反模式。 因此,以下是錯誤代碼:

class Page {

     private $container;

     public function __construct(Container $container) {
          $this->container = $container;
     }

     private function newBlock() {
          //do something here to get $filepath
          $block = $this->container['block'];
          $block->setFilePath($filepath);
          return $block;
     }

}

如何使Page具有使用DIC中定義的塊工廠的功能?

因此,在您的DI容器設置中,您可以傳遞容器引用。 因此,如果您需要在頁面類中大量使用Block類,則可以這樣做:

$container = new Container();

$container['page'] = $container->factory(function ($c) {
    return new Page( $c['block'] );
});

$container['block'] = $container->factory(function ($c) {
     return new Block();
});

但這意味着您必須向Page類的構造函數添加一個參數:

class Page {

    private $block = NULL;

    public function __construct( $block )
    {
      $this->block = $block;
    }

     private function newBlock() {
          //do something here to get $filepath
          $this->block->setFilePath($filepath);
          return $this->block;
     }

}

因此,我們實際上並不是將整個容器傳遞給每個類,而是允許DI容器根據需要傳遞對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM