1

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?

3 Answers 3

3

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.

3

Pick a PHP class in your module and define the constant in there using const keyword. For example const LOG_FILE = 'file/path';.

You can access it from anywhere like \Class\Name::LOG_FILE.

0

In your example, the best way is to create a custom logger class which implements the Psr\Log\LoggerInterface and define your path in that class (either as a constant or a pre-defined constructor variable). Then just use that class in any place you need it.

namespace My\Module\Controller;

use My\Module\Logger\DebugLogInterface;
use Magento\Backend\App\Action;

class Test extends Action
{
    protected $debugLogger;

    public function __construct(
        Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        DebugLogInterface $debugLogger
    ) {
        $this->debugLogger = $debugLogger;
        parent::__construct(Action\Context $context, \Magento\Framework\Registry $coreRegistry);
    }

    public function execute() {
        $this->debugLogger->info('We are here!');
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.