How to Add or Override Functionality to Any Package You Want
Let’s learn how you can add or override functionality to any package.
Imagine you are using a package very smoothly but after a sudden you found something you need but the package itself not providing you. May be the package fulfilling your demand 80% to 90%. In such situation what you do? How you add the functionality you need or override? There are two things you can do.
- You can fork the package and update your forked package then use forked one.
- You can make a layer or wrapper on top of the package.
So, which one will you prefer to do?
Let me explain you the trade off about these two options. If you choose 1st option you it will bit difficult to keep updated the main package inside your forked one. and 2nd option is best for us because we are using main package but just under a wrapper of us. No extra work needed.
Let me show you how you can do the 2nd option for you.
Let’s say in your package you use a class (trait or interface) to handle the functionality. As that class (trait or interface) is not fulfilling our 100% needs we are going to make a new class (trait or interface) in our project. And we will extend the package class or use the trait or implements the interface in our new class. Now if we need any extra functionality we can add easily in our class. we also can override existing functionality. In this way, we can use our new class throughout the project.
Let’s see an example:
class User
{
use MainPackageTrait // Need to update this trait
public function someFunctio()
{
//
}
}
trait OurWrapperTrait
{
use MainPackageTrait
public function newFunction()
{
//
}
public function overrideSomeFunction()
{
//
}
}
class User
{
use OurWrapperTrait // Now we are using our wrapper trait not main package trait
public function someFunctio()
{
//
}
}
Here I used PHP for example. If you are not familiar with PHP, Hope you can relate with your language too.
That’s all for now. Hope you enjoyed!
Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP