0

Below is my code how to write this code without object manager.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        //get current product
        $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
        $productId = $product->getId();
2

1 Answer 1

1

I assume you have this code in a class.
If you do, you can do this.

change the class constructor and add Magento\Framework\Registry as a parameter.
Like this:

protected $registry;
public function __construct(
    ....
    \Magento\Framework\Registry $registry,
    ...
) {
    ...
    $this->registry = $registry;
    ....
}

and now you can make your code look like

$product = $this->registry->registry('current_product');
$productId = ($product) ? $product->getId() : null;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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