Laravel Package Development Part 2 – Adding Service Provider

Laravel Package Development Part 2 - Adding Service Provider

Laravel Package Development ( 5 Lessons )

Maybe you’ve created a few apps with Laravel framework and now you want to create some re-usable code or a Laravel package. Where do you go to learn how to create a package? Yes, Right on this site!

see full series
  1. Laravel Package Development Part 1 – Introduction
  2. Laravel Package Development Part 2 – Adding Service Provider
  3. Laravel Package Development Part 3 – Adding Configuration File
  4. Laravel Package Development Part 4 – Session Class Constructor
  5. Laravel Package Development Part 5 – Shopping Cart CRUD

In the last post Laravel Package Development Part 1 – Introduction, we laid out a basic structure of package. In this post, we will start extending this package which will result in a fully functional shopping cart package.

Service Provider in Laravel

A Service Provider informs Laravel about any dependency we need to bind or resolve to the service container. You can read the this post, Service Providers in Laravel to learn more about service providers.

Creating a Service Provider

To create a service provider in Laravel run below command in the root of the application:

php artisan make:provider ShoppingCartServiceProvider

Above command will generate a ShoppingCartServiceProvider class in app/Providers folder. All you have to do is move this file inside our packages folder packages/larashout/shopping-cart/src folder.

Update the namespace of the ShoppingCartServiceProvider class from App\Providers to your package’s namespace, in my case it’s LaraShout\ShoppingCart. After changing the namespace your file should look like below:

namespace LaraShout\ShoppingCart;

use Illuminate\Support\ServiceProvider;

class ShoppingCartServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Now to register this service provider in your Laravel application, open config/app.php file and add the service provider in providers array like below:

 /*
 * Package Service Providers...
 */

LaraShout\ShoppingCart\ShoppingCartServiceProvider::class,

Creating a Shopping Cart Facade

Once you have registered the service provider, it’s time to test our package. For testing purpose, we will create a simple facade class to output some random text.

Inside your src folder, create another folder called Facades. Inside this folder create a new php file called ShoppingCartFacade. Add below code in this file.

namespace LaraShout\ShoppingCart\Facades;

use Illuminate\Support\Facades\Facade;

/**
 * Class ShoppingCartFacade
 * @package LaraShout\ShoppingCart
 */
class ShoppingCartFacade extends Facade
{
    /**
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'shoppingcart';
    }
}

Creating a Service Class

Now, we will create a new PHP class called ShoppingCart inside src/Services folder. Add the below code in the ShoppingCart service file.

namespace LaraShout\ShoppingCart\Services;

class ShoppingCart
{
    public function dump()
    {
        dd('dumping shopping cart');
    }
}

We are just adding a dump() method for testing purpose, which will simply dump a string.

Binding Facade with Service

Now we can bind our service class in the service provider’s register method. Your updated service provider will look like below:

namespace LaraShout\ShoppingCart;

use Illuminate\Support\ServiceProvider;
use LaraShout\ShoppingCart\Services\ShoppingCart;

class ShoppingCartServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('shoppingcart', function () {

            return new ShoppingCart();
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

We are getting there, last step we need to add our ShoppingCartFacade class in our config/app.php aliases array.

'aliases' => [
    ...
    'ShoppingCart' => LaraShout\ShoppingCart\Facades\ShoppingCartFacade::class,

Testing Our Facade

Now, if you open your routes/web.php file and update the main entry route from this:

Route::get('/', function () {
    return view('welcome');
}); 

to this:

Route::get('/', function () {
    ShoppingCart::dump();
    return view('welcome');
});

Now run Laravel server using command php artisan server and visit localhost:8000 in your browser, you will see the dumped message from our service class.

Final Word

Code Repository

You can get the code for this post from the Shopping Cart Repository and look for the commit marked as “service provider added”.

Until now we have successfully set up a Laravel package which we will be using to create a fully functional shopping cart. In the next post, we will start adding the shopping cart functionality to this package.

If you have any question, please leave them in the comments box below.

2 comments on “Laravel Package Development Part 2 – Adding Service Provider

  1. It’s okay so far, i am following religiously.
    In the case of wanting to build another package, will all the steps uptill now be the same, with maybe change in classes name and package folder name?

    1. Yes. To create another package follow the same steps and just change the package folder name and namespace to the new package. Make sure you do make changes in the composer.json psr-4 section.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

solid design principles in php
Why use these principles I hear you ask? When applied properly it makes your code more extendable, logical and easier...