问题
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?
回答1:
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
回答2:
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 in side your controller.
e.g use Path\to\SEOMeta;
class urclassname extends SEOMeta{
public function overridemethodname(){
// put ur logic here. }
}
来源:https://stackoverflow.com/questions/43422719/how-to-override-a-laravel-package-function