Magento – Fatal error: Uncaught Error: Call to undefined method getDirectoryRead()

admin-controllerdependency-injectionmagento2PHP

I have a controller that works and does what i need it to do if i manually add a path like: $mediaImages = '/magento/pub/media/images/';

But i cant get the DirectoryList injection to work, it returns undefined method?

<?php
  namespace Vendor\Module\Controller\Adminhtml\UpdateTable;

  class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;
    protected $_postFactory;
    protected $_filesystem;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $pageFactory,
    \NewcastleMotorcycles\AdminMenu\Model\PostFactory $postFactory,
    \Magento\Framework\App\Filesystem\DirectoryList $filesystem
    )
{
    $this->_pageFactory = $pageFactory;
    $this->_postFactory = $postFactory;
    $this->_filesystem = $filesystem;
    return parent::__construct($context);
}

public function execute()
  {
    $mediaImages = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('images/');

  }
}

The error i get is:

Fatal error: Uncaught Error: Call to undefined method
Magento\Framework\App\Filesystem\DirectoryList::getDirectoryRead()

I'm obviously missing somtehing, any advise would be great!

Best Answer

Instead of using direct object manager, use It like

use Magento\Framework\App\Filesystem\DirectoryList;

protected $_filesystem;

public function __construct(
    \Magento\Framework\Filesystem $_filesystem,
)
{
    $this->_filesystem = $_filesystem;
}

Now you can media path by,

$mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('images/');