Magento 2: Object Manager Construct Call Without Direct Call in PHTML

magento2

I need to call object manager in my phtml file but I don't want to call direct in my file.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

Please suggest

Best Answer

You can create one common helper file in your custom module

app/code/Vendor/Module/Helper/Data.php

Content for this file is..

<?php
namespace Vendor\Module\Helper;

use \Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{
    protected $_objectManager;

    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectmanager
    ) {
        $this->_objectManager = $objectmanager;
    }

    public function getObjectManager(){
        return $this->_objectManager;
    }
}

And then you can use objectManager in your phtml file using this line

<?php $objectManager = $this->helper('Vendor\Module\Helper\Data')->getObjectManager(); ?>
  • You can create block file in your custom module directory here

app/code/Vendor/Module/Block/CustomBlock.php

Content for this file is..

<?php

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;

class CustomBlock extends Template
{
    protected $_objectmanager;

    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectmanager
    ){
        $this->_objectmanager = $objectmanager;
    }

    public function getObjectManager()
    {
        return $this->_objectmanager;
    }
}

Now you need to add this class in your layout xml file like this

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\CustomBlock" name="mkt.form.jquery" template="Abc_Mkt::abc.phtml" /> 
        </referenceContainer>
    </body>
</page>

Here I've added custom block which we have created in custom module instead of using this Magento\Framework\View\Element\Template default Magento template Block.

Now you can use object manager using this line in your phtml file.

<?php $objectManager = $block->getObjectManager(); ?>

Hope this will help you!