12.15.5. कस्टम क्लास/सर्विस में डिपेंडेंसीज़ इंजेक्शन
पिछले लेखों में हमने देखा कि Services, Dependency Injection (DI) क्या हैं और उन्हें अपने कंट्रोलर, ब्लॉक और फॉर्म में कैसे उपयोग करें:
12.15. Services और Dependency Injection
12.15.1. कंट्रोलर में Dependency Injection
12.15.2. ब्लॉक में Dependency Injection
12.15.3. BaseForm में Dependencies Injection
12.15.4. ConfigFormBase कॉन्फ़िगरेशन फॉर्म में Dependencies Injection
इस लेख में हम देखेंगे कि कस्टम क्लास/सर्विस में DI के माध्यम से सर्विसेज़ कैसे जोड़ते हैं। आइए Book मॉड्यूल के उदाहरण से समझते हैं:
/core/modules/book/book.services.yml:
services:
book.manager:
class: Drupal\book\BookManager
arguments: ['@entity.manager', '@string_translation', '@config.factory', '@book.outline_storage', '@renderer']
arguments में हम बताते हैं कि हमें Service container से कौन से ऑब्जेक्ट चाहिए, इसलिए हमें अपने क्लास में create() मेथड जोड़ने की ज़रूरत नहीं होती।
/core/modules/book/src/BookManager.php:
<?php
namespace Drupal\book;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
...
/**
* Defines a book manager.
*/
class BookManager implements BookManagerInterface {
/**
* Entity manager Service Object.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Config Factory Service Object.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Books Array.
*
* @var array
*/
protected $books;
/**
* Book outline storage.
*
* @var \Drupal\book\BookOutlineStorageInterface
*/
protected $bookOutlineStorage;
/**
* Stores flattened book trees.
*
* @var array
*/
protected $bookTreeFlattened;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Constructs a BookManager object.
*/
public function __construct(EntityManagerInterface $entity_manager, TranslationInterface $translation, ConfigFactoryInterface $config_factory, BookOutlineStorageInterface $book_outline_storage, RendererInterface $renderer) {
$this->entityManager = $entity_manager;
$this->stringTranslation = $translation;
$this->configFactory = $config_factory;
$this->bookOutlineStorage = $book_outline_storage;
$this->renderer = $renderer;
}
...
}
मैंने DI से संबंधित न होने वाला कोड हटा दिया है ताकि उदाहरण को देखना आसान हो सके और यह स्पष्ट हो कि कस्टम क्लास में क्या जोड़ना है। बाकी सब कुछ सर्विसेज़ जोड़ने का तरीका कंट्रोलर जैसा ही है।