Magento 2 – Define Constants or Variables Once and Reuse in Custom Module

custommagento2modulevariables

I have a few constants that I'd like to define once and reuse many times within various files throughout my custom module. For example, I write log entries to a custom file. I'd like to add its pre-defined path in a central location and reference it from controllers, models, helpers, console commands, etc.

What's the most efficient way to do this?

Best Answer

There are different ways like:

a) helper class

1) Declare the helper class and define your constants and variables in it.

2) Inject it as a dependency in all your classes.

3) Now the constants and variables will be available in all your classes.

b) Config.xml

1) Declare your constants and variables in it.

2) You can access its values using ScopeConfigInterface.

3) If you don't know how, leave your comment and I will update my answer.

c) Class with constants and static varibles

1) Declare a Class with constants and static varibles

2) Now you can access the constants and variables without instantiating the class.

Choose as per your requirement.

Related Topic