What is Object Pool Pattern in Magento 2
An object pool is like having a collection of ready-to-use objects that you don’t have to create or get rid of manually. These objects are already there, ready for you to use in your code whenever you need them. So instead of creating and destroying objects as you go, you just grab one from the pool when you need it and put it back when you’re done. It’s like having a stash of tools that you can borrow and return without the hassle of creating or discarding them each time. Object pools provide a customized way of managing objects that are readily available for use in your code.
What is the need of the Object Pool Pattern?
- Objects are readily available without explicit creation or destruction
- Object Pools are needed to save time and resources by reusing objects instead of constantly creating and destroying them
- Objects are only loaded when needed, not during class loading.
- Object pools are handy when you want to let other parts of the program add their own information without modifying the core files, similar to how configuration providers work in Magento 2 for payment methods.
Let’s understand with one example:
Suppose we have a custom module named Test_ObjectPoolPattern. We want to create a pool of objects for a specific class, CustomObject, using the Object Pool pattern.
First, define your CustomObjectPool class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php namespace Test\ObjectPoolPattern\Model; class CustomObjectPool { /** * @var array */ private array $objects = []; /** * Get an object from the pool. * * @param string $key * @return mixed|null */ public function getObject(string $key): mixed { if (isset($this->objects[$key])) { return $this->objects[$key]; } return null; } /** * Add an object to the pool. * * @param string $key * @param mixed $object */ public function addObject(string $key, mixed $object): void { $this->objects[$key] = $object; } } |
After that we need to create configuration file di.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Test\ObjectPoolPattern\Model\CustomObjectPool"> <arguments> <argument name="objects" xsi:type="array"> <!-- Configure objects in the pool --> <item name="object1" xsi:type="object">Test\ObjectPoolPattern\Model\CustomObject</item> <!-- Add more items as needed --> </argument> </arguments> </type> </config> |
Implement the CustomObject class:
1 2 3 4 5 6 7 8 |
<?php namespace Test\ObjectPoolPattern\Model; class CustomObject { // Implement your custom object logic here } |
Now, you can inject CustomObjectPool into any class and retrieve instances of CustomObject from the pool using the getObject() method.
Manjeet Maurya
2024-03-13