Laravel Package Development Part 4 – Session Class Constructor

Laravel Package Development Part 4 – Session Class Constructor

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 fourth part of our Laravel Package Development series. In this post, we will start adding shopping cart methods to Session class.

As I promised, we will be storing the shopping cart data either in session or database. Firstly we will implement our Session class in this post and in the next post will look at storing data to database.

In the last part of this series, we added a configuration file which will return the storage type for our shopping cart. Go ahead and change the storage value to session in shoppingcart.php file if you have set it up to database.

Adding Session Class Constructor

To store our shopping cart data in sessions, we will need to add some Laravel’s core classes to our Session class. Open your Session class file (packages/larashout/shopping-cart/src/Services/Session.php) and include below code:

use Illuminate\Support\Collection;
use Illuminate\Session\SessionManager;
use Illuminate\Contracts\Events\Dispatcher;

Using above code, we have added Laravel’s collection class, a session manager class and a dispatcher class. You must be wondering, why we have added the dispatcher class. So the answer is, when we are using the shopping cart we want to fire some events which other users can catch while using your shopping cart package. For example, when we add a product to shopping cart we might want to fire couple of events like:

  • Cart adding
  • Cart added
  • Cart updating
  • Cart deleting
  • and so on…

Next we added the Collection class as our cart will returning an instance of a collection and finally SessionManager, which will allow us to store data in the session.

After adding these classes, your Session class will look like below:

namespace LaraShout\ShoppingCart\Services;

use Illuminate\Support\Collection;
use Illuminate\Session\SessionManager;
use Illuminate\Contracts\Events\Dispatcher;

class Session
{
    //
}

Please note that, I have removed the dump() method, which we added in the last post for testing.

Now we need to add the constructor to Session class and inject the Laravel core classes we want to use. For that, firstly we need to add some properties to our class.

Add below code into your Session class.

protected $session;

protected $event;

protected $name = 'cart.session';

public function __construct(SessionManager $session, Dispatcher $event)
{
    $this->session = $session;

    $this->event = $event;
}

In above code example, we are defining some properties like $session, $event, $name and adding a constructor to inject the SessionManager and Dispatcher classes into Session class.

Adjusting Service Provider register() Method

As you know, in the last post we added the below code in the register() method of ShoppingCartServiceProvider class.

/**
 * 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();
        });
    }
}

As we have defined a constructor to our Session class, we need to pass the arguments to return new Session();.

Note

If you try to use Session class it will thorugh an error something like this : Too few arguments to function LaraShout\ShoppingCart\Services\Session::__construct(), 0 passed in .

We are injecting our Session and Database class using the Laravel’s container, which provide us the $app instance of the application. So we can use $app['session'] and $app['events'] to our Session class. $app['session'] provide an instance of Session Manager and $app['events'] provide an instance of Dispatcher class.

Now our register() method will look like below:

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

Adding all() Method to Session Class

Now, I want to add a all() method to Session class which will be accessable like below and should return all items in the shopping cart:

ShoppingCart::all();

Before adding all() method, we will add some getter and setter methods for $name property which will return the name of shopping cart.

Add below code right after the constructor of Session class.

public function name($name)
{
    $this->name = $name;
    return $this;
}

public function getName()
{
    return $this->name;
}

name() method is setting the $name (setter) value and getName() will return the $name (getter).

Now we will add all() method like below:

public function all()
{
    return $this->getCart();
}

Our all() method will return another method called getCart() which will return us the shopping cart from session.

Now, we will add a protected method called getCart().

protected function getCart()
{
    $cart = $this->session->get($this->name);

    return $cart instanceof Collection ? $cart : new Collection();
}

Above method is getting the shopping cart data by passing the shopping cart name ($this->name) to the session manager. After getting the shopping cart we are checking if $cart is an instance of the Illuminate\Support\Collection class, if yes return $cart otherwise return a new collection which will be empty.

Now if you try to use all method ShoppingCart::all() of shopping cart it will return an empty collection as we don’t have anything in the shopping cart.

Code Repository

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

In this next part of this series, we will start adding, updating and deleting items into the shopping cart.

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.