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.

:bulb:Did you enjoy this blog post?

If so, please consider checking out my side project Domain Clamp. It's a SaaS which monitors domains and SSL certificates and sends notifications before anything expires. If you work at an agency, then you're probably not the registrant for your client's domains or the SSL certificate owner. This means you won't get expiration notifications. You don't want a client's domain or SSL certificate to expire under your watch. Believe me, I've been there.

Domain Clamp solves this problem by letting you monitor the SSL certificate and registration for any domain you'd damn please. Free accounts are available so please head on over »