How to store variables in the flag table Magento parts involve this table as key-value storage for any information if the extra creation table is above. As a Magento developer, we prefer to store data like configuration variables inside core_config_data
. However, it has cache constraints.
The table core_config_data
involves the configuration cache, which is good. However, Magento also provides the table flag
to store variables as key-value pairs.
Let’s see how we can store variables in the flag
table.
namespace SbDevBlog\FlagExample\Services;
use Magento\Framework\FlagManager;
class SaveToFlagService
{
private FlagManager $flagManager;
public function __construct(
FlagManager $flagManager
) {
$this->flagManager = $flagManager;
}
/**
*. Set Configuration Value
*
*. @param string $flagCode
*. @param mixed $value
*
* @return void
*/
public function setConfigFlagValue($flagCode, $value):void
{
$this->flagManager->saveFlag($flagCode, $value);
}
/**
* Get Configuration Value From Flag By Code
*
* @param string $flagCode
*
* @return mixed
*/
public function getConfigFlagValue($flagCode):mixed
{
return $this->flagManager->getFlagData($flagCode);
}
}
This is the simplest way to set and get custom variables from the table flag
.
We have injected the class Magento\Framework\FlagManager
in our constructor and initialised it in our class variable flagManager
.
In the method setConfigFlagValue
, we have saved the variable into the table with the name flag
by passing $flagCode
as the string type of the variable and mixed value as the $value
parameter.
The method getConfigFlagValue
is used to get the configuration value from the table flag
. We need to pass $flagCode
as the parameter, which is a string. We will get the value according to the variable we have passed as $flagCode
That’s it. I hope you like this article. Let’s use the Flag
table for necessary data storage instead of creating a new table or using the core_config_data
table.
Thanks for reading the article. How to store variables in the flag table: Please share your valuable suggestions in the comment box. Also, please share https://sbdevblog.com with your connections.
Let’s help each other. #HelpingHand. Stay tuned for new posts. Thank you again.
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂
One thought on “Magento 2: How to store variables in the flag table?”