Build and publish your own Laravel package

Build and publish your own Laravel package

·

3 min read

What is Package ?

Package is a stand-alone source code which we can import into our different projects using a package management tool like a composer (in the case of PHP).

Why is it needed?

Many developers reuse the same source code by copy-pasting code in different projects. In the case of vulnerability use or bug fix, we need to fix all projects. So better build your custom package and maintain it in version control (such as git).

Creating Custom Package

Let's build a simple PHP (composer) package, a Japanese date formatter.

Prerequistites

Before starting you must have installed Composer https://getcomposer.org/doc/ and Git in your system. Scaffold a new laravel project.

Package Structure

Screen Shot 2021-10-31 at 18.01.13.png

Here, I create packages directory and {vendor name} directory followed by {package directory name}. The src folder will contain all of our source code and create dist for distribution files when installing your package through composer.

Initializing package composer

Navigate the src path from the command and then initialize the package folder

$ composer init

This command will ask to create a composer.json, a configuration file for the composer. Screen Shot 2021-10-31 at 18.02.29.png

After the initialization, the system will create the composer.json file inside the package folder Screen Shot 2021-10-31 at 18.08.04.png

Package Discovery for Laravel

To make the package installation process easy we can add service provider in our composer.json file. When someone installs our package, they typically want Laravel's service provider to be loaded automatically instead of manually adding our service provider to the config file. For this, we need to define the provider in the extra section.

"extra": {
    "laravel": {
        "providers": [
            "Ashokgrg\\JpDateFormatter\\JpDateFormatterServiceProvider"
        ]
    }
},

Service Providers JpDateFormatterServiceProvider.php Class

Let's create our service provider class file inside the src directory

<?php
namespace Ashokgrg\JpDateFormatter;
use Illuminate\Support\ServiceProvider;
class JpDateFormatterServiceProvider extends ServiceProvider
{

    public function boot()
    {
        dd("Its works");
    }
    public function register()
    {

    }

}

Add package in existing project and check its works or not

Edit the parent composer.json file of our project define the package information

"repositories": {
    "jp-date-formatter": {
        "type": "path",
        "url": "packages/ashokgrg/jp-date-formatter",
        "options": {
            "symlink": true
        }
    }
},

inside the require object let's include our the package

"require": {
    "ashokgrg/jp-date-formatter": "@dev"
},

Composer update

After that, run the composer update command in the root directory. It will create our package folder inside the root vendor directory and check the application. We can check if it works text in the browser.

Screen Shot 2021-10-31 at 20.20.08.png

Modification JpDateFormatter.phpClass

Let's create our date formatter class inside the src and define the method.

<?php
namespace Ashokgrg\JpDateFormatter;
class JpDateFormatter
{
public static function format(string $date): string
{
    $year                 = date('Y', strtotime($date));
    $month                = date('m', strtotime($date));
    $day                  = date('d', strtotime($date));
    return $year."年".$month."月".$day."日";
}

}

JpDateFormatterServiceProvider.php Laravel Service Provider Class

Let assign a method from the service provider that returns singleton class

<?php
namespace Ashokgrg\JpDateFormatter;
use Illuminate\Support\ServiceProvider;

class JpDateFormatterServiceProvider extends ServiceProvider
{

    public function boot()
    {
    }
    public function register()
    {
      $this->app->singleton(JpDateFormatter::class, function(){
          return new JpDateFormatter();
      });
    }

}

Locally Testing

Let's test our package by adding a new route that returns today's date

<?php
Route::get('/test', function () {
    return JpDateFormatter::format(Carbon::now());
});

Test Result

Screen Shot 2021-10-31 at 20.53.26.png

Publishing Package

Now, time to push our package in GitHub and publish our package publicly. Here I push our demo package in my GitHub account. Then log in to packagist.org (packagist.org) with our account and click submit button and paste your GitHub repo and then submit.

Screen Shot 2021-10-31 at 21.48.22.png

Reference

https://laravel.com/docs/8.x/packages

https://medium.com/cafe24-ph-blog/build-your-own-laravel-package-in-10-minutes-using-composer-867e8ef875dd

https://medium.com/@andrewhanks2402/step-by-step-guide-to-laravel-package-development-82e2865fb278