'Magento2 - how do I call a function in another class?

I'm creating an observer and I'm trying to connect it to saving a new product. If the product is new I'm trying to run a code, if not - skip.

I made an observer before save in creating a new product and after that I want to run the same code as shared catalog -> shared catalogs -> default -> set pricing and structure -> and just save without changing anything.

This is my code:

NewProductReindexer/etc/adminhtml/events.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_before">
    <observer name="Company_module_event_after_observer" instance="Company\NewProductReindexer\Observer\NewProductObserver"/>
</event>

Observer/NewProductObserver.php

class NewProductObserver implements ObserverInterface
{


    public function __construct()
    {

    }

    public function execute(Observer $observer)
    {

    $isProductNew = $product->isObjectNew();

    if($isProductNew == true){
        //new product

    }else{
       relax();

    }


    }
}


Solution 1:[1]

The two ways to call you a block class method in the custom module class

  1. using constructor dependency like that
public function __construct(Namespace\ModuleName\Helper\Data $helper)
   {
           $this->helper = $helper;
   }
   public function MyFunction()
   {               $this->helper->HelperDemo();
   }
  1. using method dependency public function execute(Namespace\ModuleName\Helper\Data $helper) { $helper->HelperDemo(); }

For more detail visit the below link https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LitCommerce Expert