Mehdi
Mehdi

Reputation: 373

How to override a Laravel package function

I'm using https://github.com/artesaos/seotools package for seo. I am trying to override getCanonical function located at https://github.com/artesaos/seotools/blob/master/src/SEOTools/SEOMeta.php and make it's output as lowercase. Could you please guide me how can I do this?

Upvotes: 4

Views: 6924

Answers (2)

rajesh
rajesh

Reputation: 49

It's very simple just like we overriding any parent class function in derived class.

Create your own class and extend your package class SEOMeta and re-declare function that you want to override and put your logic inside. Don't forget to use namespace of your package class SEOMeta at upper your custom class.

Now use your custom class instead of package class inside your controller.

e.g

use Path\to\SEOMeta;

class urclassname extends SEOMeta{

    public function overridemethodname(){

        // put ur logic here.
    }

}

Upvotes: 2

Pankit Gami
Pankit Gami

Reputation: 2553

You can try following :

Step 1:

Create a child class extending SEOMeta class and override the getCanonical function.

Class XyzSEOMeta extends SEOMeta {
    public function getCanonical () {
       // Write your logic here
    }
}

Step 2:

Create the Service Provider for overridden class. First parameter of bind function must be same as facade accessor of SEOMeta Facade (check here). Register this facade in config/app.php after the service provider of seotools package. :

Class XyzSEOMetaServiceProvider extends ServiceProvider {
    public function register(){
        $this->app->bind('seotools.metatags', function(){
           return new XyzSEOMeta($this->app['config']);
        })
    }
}

You are all set. Hope this will help.

EDIT:

Above mention method will just override the single class. If you want to change the logic of more than one class. Best way is to fork the project. Change the code and push it to your fork. Use forked project as your composer dependency. Follow the link to know how to use private repository as composer dependency : https://getcomposer.org/doc/05-repositories.md#using-private-repositories

Upvotes: 5

Related Questions