Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using other packages inside my laravel package [closed]

I created a package with the artisan workbench command. Everything works fine, but I want to use another composer package inside my package. What's the best/cleanest way to do that?

like image 419
Rai Avatar asked Oct 21 '22 01:10

Rai


1 Answers

Basically you just have to require the package in your package composer.json and instantiate it in your service provider, injecting that package into your class:

class MyPackageServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app['mypackage'] = $this->app->share(function($app)
        {
            return new MyPackage(
                new ThirdPartyPackage()
            );
        });
    }

}

And use it in your class:

class MyPackage {

    public function __construct(ThirPartyPackage $package) 
    {
        $this->package = $package
    }

    public function doWhatever() 
    {
        $this->package->do();
    }    
}

If the package has only static functions, there is not much that can be done, you'll probably have to use it directly in your classes:

Unirest::get("http://httpbin.org/get", null, null, "username", "password");

Something you can do is to create a class to dinamically use that package:

class MyRest implements MyClassInterface {

    public function get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL)
    {
        return Unirest::get($url, $parameters, $headers, $username, $password);
    }

}

And use your own class in your package. By not exposing that package directly you can use it dinamically and still be able to change the implementation later. You should also create an interface to for your public methods:

interface MyClassInterface {

   public function get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL);

}
like image 120
Antonio Carlos Ribeiro Avatar answered Oct 24 '22 13:10

Antonio Carlos Ribeiro