How to get access to working directories in Magento 2
To get access to working directories in Magento 2, you can declare the class in __constract:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
protected $_dir; ... public function __construct( ... \Magento\Framework\Filesystem\DirectoryList $dir, ... ) { ... $this->_dir = $dir; ... } |
Use the method to perform the actions:
– get the root directory of Magento 2:
1 |
$this->_dir->getRoot(); |
– or any working Magento 2 directory:
1 |
$this->_dir->getPath(‘var’); |
– connect url to it:
1 |
$this->_dir->getUrlPath(‘media’); // return relative url – 'pub/media' |
You can rely on the following working directories since they are available as arguments:
1 |
base, app, code, etc, lib_internal, var, cache, log, di, generation, i18n, session, media, static, pub, lib_web, tmp, sys_tmp, design, upload, view_preprocessed, html, setup. |
More tips from Magento 2 Developer’s Cookbook