Laravel extension package development

This example takes hinet/ laravel-Invitecode, an invitation code project I created on Github, as an example.

About the source

Hinet/laravel-Invitecode: Invite Code for Laravel (github.com)

Extension Package Directory

Create the packages directory in the project root directory and create a directory named packages under that directory with the following structure:

|- App
|- packages
|---- laravel-invitecode
|-------- config 
|-------- src 
|-------- composer.json
Copy the code

Initialize the

We use the Composer init command to initialize the creation package

composer init
Copy the code

Run the preceding command and fill in the package information as prompted. The resulting composer. Json content is as follows:

{
    "name": "hinet/laravel-invitecode"."description": "invite code for laravel"."keywords": ["invite code"."laravel"]."require": {
        "php": "7.3 | ^ ^ 8.0"."illuminate/support": 7.0 | 6.0 | 5.5 | "^ ^ ^ ^ 8.0 | ^ 9.0"
    },
    "license": "MIT"."autoload": {
        "psr-4": {
            "Hinet\\InviteCode\\": "src/"}},"authors": [{"name": "hinet"."email": "[email protected]"}]."minimum-stability": "dev"
}

Copy the code

Note: We need to create a Facade and Provider later, so the Illuminate/Support package needs to be introduced

Add a third-party class library

Since we need to use the third-party HashId class library to generate the invitation code in the extension package, we need to add the Classmap node under the Autoload node of composer. Json to automatically load the class library, we copy the class library to the SRC /Libs directory of the extension package. And modify composer. Json as follows:

{
    "name": "hinet/laravel-invitecode"."description": "invite code for laravel"."keywords": ["invite code"."laravel"]."require": {
        "php": "7.3 | ^ ^ 8.0"."illuminate/support": 7.0 | 6.0 | 5.5 | "^ ^ ^ ^ 8.0 | ^ 9.0"
    },
    "license": "MIT"."autoload": {
        "classmap": [
            "src/Libs/HashGenerator.php"."src/Libs/Hashids.php"]."psr-4": {
            "Hinet\\InviteCode\\": "src/"}},"authors": [{"name": "hinet"."email": "[email protected]"}]."minimum-stability": "dev"
}
Copy the code

Create a captcha generation class

Create our captcha generation class invitecode.php in the SRC directory as follows:


      
namespace Hinet\InviteCode;

use Hashids;
use Illuminate\Config\Repository;

/** * invitation code generation class */
class InviteCode{
    protected $config;
    private $hashIds;

    public function __construct(Repository $config){
        $this->config = $config->get('invitecode');
        $salt = $this->config['salt'];
        if(empty($salt)) {$salt = env('APP_KEY');
        }
        // Instantiate the HashIds library
        $this->hashIds = new Hashids($salt.$this->config['length'].$this->config['char']);
    }
    /** * Generates an invitation code */
    public function enCode($id){
        return $this->hashIds->encode($id);
    }
    /** * Obtain the user ID */ based on the invitation code
    public function deCode($code){
        $code = $this->hashIds->decode($code);
        if(is_array($code)) {return current($code);
        }else{
            return $code; }}}Copy the code

Creating a Configuration File

Create the config directory in the extension package root directory and create the config file config.php as follows:


      
return   [
    'length'= >6.// The length of the invitation code
    'char'= >' '.// Generate the invitation character (cannot include 0), default a-za-z1-9
    'salt'= >' '.// Encryption salt, default use APP_KEY
];
Copy the code

Create a Provider service Provider

Create the InviteCodeProvider by executing the artisan command in the project root directory.

php artisan make:provider InviteCodeProvider
Copy the code

The generated provider will be in the App/Providers directory of the project. We will copy it to the SRC/extension package and modify the namespace accordingly. The final code is as follows:


      

namespace Hinet\InviteCode;

use Illuminate\Support\ServiceProvider;

class InviteCodeProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {        
        // Register an instance of the InviteCode class in singleton mode. Note that it is registered as InviteCode and the Facade behind it will be named after InviteCode, otherwise the instance of the class will not be found
        $this->app->singleton('InviteCode'.function ($app) {
            return new InviteCode($app['config']);
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        // Automatically publish the configuration file, where invitecode parameter is tag
        $this->publishes([
            __DIR__.'/.. /config/config.php' => config_path('invitecode.php')],'invitecode'); }}Copy the code

Create a Facade

Create the SRC /Facades directory in the extension package and create invitecode.php as follows


      
namespace Hinet\InviteCode\Facades;

use Illuminate\Support\Facades\Facade;
class InviteCode extends Facade
{
    protected static function getFacadeAccessor()
    {
        // Note that the Facade name must be the same as the name of the singleton registered in the Provider
        return 'InviteCode'; }}Copy the code

Extension Pack Discovery

In the Laravel app’s config/app.php configuration file, the providers option defines the list of service providers that Laravel can load. When someone installs your extension pack, they usually want to include your service provider in this list. Instead of having users manually add your service providers to the list, you can define service providers in the Extra section of the composer. Json file in the extension package. In addition to service providers, you can list all the Facades you want to register:

{
    "name": "hinet/laravel-invitecode"."description": "invite code for laravel"."keywords": ["invite code"."laravel"]."require": {
        "php": "7.3 | ^ ^ 8.0"."illuminate/support": 7.0 | 6.0 | 5.5 | "^ ^ ^ ^ 8.0 | ^ 9.0"
    },
    "license": "MIT"."autoload": {
        "classmap": [
            "src/Libs/HashGenerator.php"."src/Libs/Hashids.php"]."psr-4": {
            "Hinet\\InviteCode\\": "src/"}},"extra": {
        "laravel": {
            "providers": [
                "Hinet\\InviteCode\\InviteCodeProvider"]."aliases": {
                "InviteCode": "Hinet\\InviteCode\\Facades\\InviteCode"}}},"authors": [{"name": "hinet"."email": "[email protected]"}]."minimum-stability": "dev"
}
Copy the code

At this point, a Laravel extension pack has been developed.

Distributing extension packages

Create the repository on Github, push the extensions we created into the repository, and publish our extensions at www.packagist.org to install in Composer.

Installing the Extension Package

We can install the Laravel extension package we just released using the composer command:

composer require hinet/laravel-invitecode
Copy the code

Publishing configuration in a project:

PHP artisan Vendor :publish --tag=invitecode #Copy the code

Use the sample

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use InviteCode;
class DemoController extends Controller{
    public function index(){
        echo InviteCode::enCode(123);
        //print NDZ0kA
        //echo echo InviteCode::deCode('NDZ0kA');
        //print 123}}Copy the code