Accessing the admin front name programmatically in Magento 2

Published: March 23, 2017

Tags:

Recently I was working on some Magento 2 code where I needed to programmatically determine the admin front name. If you run a Google search you’ll pretty quickly find the canonical answer for Magento 1

Mage::getConfig()->getNode('admin/routers/adminhtml/args/frontName')

However, even after reading through two pages of Google results, I was not able to find an answer for Magento 2.

I decided to dig into the code myself and found that Magento\Framework\App\AreaList seems to be the best solution. Specifically the getFrontName method will give you the answer you need if you pass “adminhtml” as the $areaCode argument.

Here’s a quick example of how an implementation looks…

<?php

namespace Mpchadwick\Foo\Model;

use Magento\Framework\App\AreaList;

class Bar
{
    public $adminFrontName;
    
    public function __construct(AreaList $areaList)
    {
        $this->adminFrontName = $areaList->getFrontName('adminhtml')        
    }
}

Conclusion

If you have any questions or comments, feel free to drop a note below, or, as always, you can reach me on Twitter as well.

Max ChadwickHi, I'm Max!

I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.

During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.

If you'd like to get in touch with me the best way is on Twitter.