3

I am new to Magento development and I am using a custom MySQL query in some places like in observer/plugin etc.

These codes are repeating for all these files. so I want to make a new reusable function/class and want to call this method instead of writing the same thing in all files.

I don't know even to create controller and all, could you please help me to create this?

                $modelMaterials = $objectManager->create('Vendor\Module\Model\Grid');
                $dataMaterials=$modelMaterials->getCollection()->addFieldToFilter('entity_id', array('in' => array($material_id)))->setPageSize(1)->setOrder('entity_id','DESC');;
                if($dataMaterials->getSize()){
                     $materialsarr = $dataMaterials->getFirstItem();
                     $weight = $subject->getWeight();
                     $fineWeight = $data->getFineWeight();
                     $metalPrice = (double)$materialsarr->getAmount() * ((float)$weight + (float)$fineWeight);
                     $metalPrice += (double)$data->getSurcharge();
                     $metalValue = (double)$materialsarr->getAmount() * ((float)$weight + (float)$fineWeight);
                     $price = (double)$materialsarr->getAmount() * (double)$weight;
                     $tx_rates = (double)$materialsarr->getTax() / 100;
                     $tax = $tx_rates * (double)$metalPrice;
                     $specialPrice = $subject->getSpecialPrice();
                }      
3

The Magento 2 helper is the class which is used for adding functionalities to several features and can be used anywhere in the entire website. They are created as Singleton (single instances of objects) which can be called in controllers, views, models, templates etc.

Create Magento 2 Custom Module
Add module.xml file in app/code/Magenticians/Mymodule/etc and copy the following code in it:

<?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
                        <module name="Magenticians_Mymodule" setup_version="1.0.1">
                        </module>
            </config>

Add registration.php in app/code/Magenticians/Mymodule and copy the following code in it:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Magenticians_Mymodule',
__DIR__
);

Create Magento 2 Helper Now add Data.php file in app/code/Magenticians/Mymodule/Helper and copy the following code in it:

<?php

namespace Magenticians\Mymodule\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Http\Context $httpContext
    ) 
    {
        parent::__construct($context);
        $this->httpContext = $httpContext;
    }

    public function isLoggedIn()
    {
        $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
        return $isLoggedIn;
    }
}

and observer file how to helper class call

<?php

namespace Magenticians\Mymodule\Observer;

use Magento\Framework\Event\ObserverInterface;

class Mymodulename implements ObserverInterface
{
    ...

    protected $dataHelper;

    ...

    public function __construct(
        ...
        \Magenticians\Mymodule\Helper\Data $dataHelper
        ...
    ) {
        ...
        $this->dataHelper = $dataHelper;
        ...
    }

    public function ...(){
        $helper = $this->dataHelper->isLoggedIn();
    }

    ...
}

?>
  • Great! this is what i am looking for, but can you provide a example for calling this from a observer/plugin? now you gave me the phtml file. – Sanjun Dev Sep 20 at 9:18
3

Create a helper class and define in function in helper. Then you can use where ever in those Magento project.

Helpers are usually used as elements that are global and always available.

Magento 2 Helper contains functions and methods that are commonly used throughout the application. Methods that are declared as Helpers can be called from any template file, block, model, controller class or even from another helper in Magento 2.

For more detail refer: https://www.mageplaza.com/devdocs/create-helper-class-magento-2.html

Updated solution:

you can get helper class valuea in template like below code

$this->helper('Vendor\Module\Helper\Data')->methodname();
2

For using common function, the best approach is to create a custom module and use Magento 2 Helper which gives you one of the best opportunities to override core files and pre-defined functions of the Magento 2 platform.

The Magento 2 helper is the class which is used for adding functionalities to several features and can be used anywhere in the entire website. They are created as Singleton (single instances of objects) which can be called in controllers, views, models, templates etc.

For example, You can use the above code in your helper and inject your helper class anywhere in the code to get the data from the code.

For more detailed information you can visit this link.

EDIT:

You can use the below code in your observer for adding helper class.

<?php

namespace Custom\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class SalableObserver implements ObserverInterface
{
    protected $dataHelper;

    public function __construct(
        \Custom\Module\Helper\Data $dataHelper
    ) {
        $this->dataHelper = $dataHelper;
    }

    public function yourFunction(){
        $helper = $this->dataHelper;
    }
}

?>

Hope it helps!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.