Laravel Package Development Part 3 – Adding Configuration File

Laravel Package Development Part 3 - Adding Configuration File

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

This is the third part of our Laravel Package Development series. In this post, we will add a configuration file to our shopping cart package.

Why Configuration File?

Suppose we want to add the ability to switch the storage driver for our shopping cart. We can either store cart data in session or in a database table. Laravel provides the ability to define our own configuration file right into our package.

Creating a Configuration File

Firstly we will create a configuration file which can be published with the package into Laravel application. Go ahead and create a new folder inside src folder and name it config.

Inside config folder, we will create a new PHP file called shoppingcart.php. Inside this file, we will return an array which will provide the storage driver type for our package.

return array(
    'storage' => 'session', // session or database
);

Publishing Configuration File

Now we will define in our ShoppingCartServiceProvider to publish our configuration file. To achieve this, we will modify the boot() method of service provider and add the below line of code.

$this->publishes([
   __DIR__.'/config/shoppingcart.php' =>  config_path('shoppingcart.php'),
], 'config');

To publish our file into Laravel’s config folder, run the below command:

php artisan vendor:publish

When you hit the above command in terminal, you will be provided a list of all service providers registered in your application. Choose the LaraShout/ShoppingCartServiceProvider and hit enter.

Now if you check your config folder, you will find your shoppingcart.php file in there.

Creating Session and Database Service Files

For our shopping cart we are going to use both session and database storage type, we need to create these two service files.

In the last post, we created a service file called ShoppingCart in services folder. You can go ahead and delete it.

In the services folder (packages/larashout/shopping-cart/src/Services), we will create two files (session.php and database.php) as below:

namespace LaraShout\ShoppingCart\Services;

class Session
{
    public function dump()
    {
        dd('using session');
    }
}
namespace LaraShout\ShoppingCart\Services;

class Database
{
    public function dump()
    {
        dd('using database');
    }
}

Next, in our ShoppingCartServiceProvider we will add a new method called getStorageService() which will return the storage type based on our configuration file.

Go ahead and add the below method in ShoppingCartServiceProvider class.

/**
     *  Get the storage settings based on config file
     *
     * @return string
     */
    public function getStorageService()
    {
        $class = $this->app['config']->get('shoppingcart.storage','session');

        switch ($class)
        {
            case 'session':
                return 'session';
            break;
            case 'database':
                return 'database';
            break;
            default:
                return 'session';
            break;
    }
}

Above method is self-explanatory, we are getting the storage value from the configuration file and passing it to a switch statement which will return the correct storage type. By default, we are setting storage type to session.

Now we will adjust our register() method which will bind the selected service (either Session or Database) in Laravel’s service container.

Firstly add the both services into service provider like below:

use LaraShout\ShoppingCart\Services\Session;
use LaraShout\ShoppingCart\Services\Database;

An then, update register() method with below.

/**
     * Register services.
     *
     * @return void
     */
public function register()
{
    if ($this->getStorageService() == 'session')
    {
        $this->app->singleton('shoppingcart', function($app) {
            return new Session();
        });
    } else
    {
        $this->app->singleton('shoppingcart', function($app) {
            return new Database();
        });
    }
}

Last Thing

Now our both services are injected into Laravel’s service container, go ahead and add ShoppingCart::dump(); anywhere in Laravel application and it will return the message based on the storage type we have defined in the configuration file.

Code Repository

You can get the code for this post from the Shopping Cart Repository.

In the next part of this series, we will start adding functionality to our session and database services.

If you have any question, please leave it in the comment box below.

Your little help will keep this site alive and help us to produce quality content for you.