How to Check If Third Party Library Exists or not in Magento 2

Check If Third Party Library Exists or not in Magento 2

Magento 2 works with numerous third-party libraries and also accommodates for external libraries undoubtedly!

If you are looking forward to extend default Magento functionality with the third party APIs, you require to include external libraries in your extension or feature. Third-party libraries are a great way to add complex features or functionality to your Magento 2 extensions quickly. Payment gateways, shipping API, social networking, all provide their language-specific library, which we need to include in our Magento extension to connect with them.

Let’s take an example where you require the users to install a third party library using composer. What if the users forget to install the library and start making use of the extension? Obviously, the extension will stop working at some point or may generate an error due to non-existence of the third party library.

To avoid the situation, I’ve come up with the solution to check if third party library exists or not in Magento 2. Using the steps, you can create an event to check existence of the third party library and set restriction error to further working of the functionality until the library is installed.

Steps to Check If Third Party Library Exists or Not in Magento 2

First of all, decide the location where you need to check the availability of a third-party library.

The core part of checking availability is the class_exists function that can be used as below.

Let’s comprehend this post with one live example:

You want to check the existence of the 3rd party library while someone saves the extension configuration. Here, events and observers take place to set up the restriction.

In admin_system_config_changed_section_sms event, pass an observer which is going to check the availability of third party library.

Here is the code to pass the event. For more event lists and how they are used, you can refer Magento 2 Events.

Pass the observer code like below in Vendor\Extension\Observer

That’s all!

Setting a simple validation can save you a lot of support queries, right?!

Any doubts on this topic can be discussed in the Comments section below. I’d be happy to solve them.

Feel free to share the above solution with fellow developers via social media.



Get Weekly Updates

Never miss Magento tips, tricks, tutorials, and news.

Thank you for subscribing.

Something went wrong.

(based on 11 Reviews)

He is a Magento developer at Meetanshi with a jolly, extrovert, & friendly personality. He loves playing cricket and is a passionate foodie!

Leave a reply:

Your email address will not be published.