PHP code example of nyoncode / laravel-package-toolkit

1. Go to this page and download the library: Download nyoncode/laravel-package-toolkit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nyoncode / laravel-package-toolkit example snippets


use NyonCode\LaravelPackageToolkit\PackageServiceProvider;
use NyonCode\LaravelPackageToolkit\Packager;
use NyonCode\LaravelPackageToolkit\Contracts\Packable;

class MyAwesomePackageServiceProvider extends PackageServiceProvider implements
    Packable
{
    public function configure(Packager $packager): void
    {
        $packager
            ->name('My Awesome Package')
            ->hasConfig()
            ->hasRoutes()
            ->hasMigrations()
            ->hasTranslations()
            ->hasViews();
    }
}

use NyonCode\LaravelPackageToolkit\PackageServiceProvider;
use NyonCode\LaravelPackageToolkit\Packager;
use NyonCode\LaravelPackageToolkit\Contracts\Packable;

class AdvancedPackageServiceProvider extends PackageServiceProvider implements
    Packable
{
    public function configure(Packager $packager): void
    {
        $packager
            ->name('Advanced package')
            ->hasShortName('adv-pkg')
            ->hasConfig('custom-config.php')
            ->hasRoutes(['api.php', 'web.php'])
            ->hasMigrations('custom-migrations')
            ->hasTranslations('lang')
            ->hasViews('custom-views')
            ->hasComponents([
                'data-table' => DataTable::class,
                'modal' => Modal::class,
            ]);
    }

    public function registeringPackage(): void
    {
        // Custom logic before package registration
    }

    public function bootingPackage(): void
    {
        // Custom logic before package boot
    }
}

use NyonCode\LaravelPackageToolkit\PackageServiceProvider;
use NyonCode\LaravelPackageToolkit\Packager;
use NyonCode\LaravelPackageToolkit\Contracts\Packable;

class ConditionalPackageServiceProvider extends PackageServiceProvider implements
    Packable
{
    public function configure(Packager $packager): void
    {
        $packager
            ->name('Conditional package')
            ->hasRoutes(['api.php', 'web.php'])
            ->hasMigrations('custom-migrations')
            ->hasTranslations('lang')
            ->hasViews('custom-views')
            ->when($this->isInLocal(), function ($packager) {
                $packager->hasConfig('local-config.php');
                $packager->hasCommands();
            })->when($this->isInProduction(), function ($packager) {
                $packager->hasConfig('production-config.php');
                $packager->hasRoutes('web.php');
            });
    }
}

$packager
    // Environment-based conditions
    ->whenEnvironment(['local', 'testing'], function ($packager) {
        $packager->hasCommands(['DevCommand::class']);
    })
    ->whenProduction(function ($packager) {
        $packager->hasConfig('production-config.php');
    })
    ->whenLocal(function ($packager) {
        $packager->hasConfig('local-config.php');
    })
    
    // Runtime conditions
    ->whenConsole(function ($packager) {
        $packager->hasCommands();
    })
    
    // Class/extension existence
    ->whenClassExists('SomeClass', function ($packager) {
        $packager->hasConfig('optional-config.php');
    })
    ->whenExtensionLoaded('redis', function ($packager) {
        $packager->hasConfig('redis-config.php');
    });

$packager
    ->name('My Package')
    ->registeringPackage(function ($packager) {
        // Logic executed before package registration
        Log::info('Registering My Package');
    })
    ->registeredPackage(function ($packager) {
        // Logic executed after package registration
        $this->app->singleton('my-service', MyService::class);
    })
    ->bootingPackage(function ($packager) {
        // Logic executed before package boot
        Event::listen('my-event', MyListener::class);
    })
    ->bootedPackage(function ($packager) {
        // Logic executed after package boot
        Log::info('My Package fully loaded');
    });

$packager->name('Package name');

$packager->hasShortName('custom-short-name');

$packager->hasConfig();

$packager->hasConfig(['config.php', 'other-config.php']);

$packager->hasConfig([
    '../www/config/config.php',
    '../api/config/other-config.php',
]);

$package->hasConfig(directory: 'customConfig');

$packager->hasRoutes();

$packager->hasRoutes(['api.php', 'web.php']);

$packager->hasRoute(['../www/routes/web.php', '../api/routes/api.php']);

$package->hasRoute(directory: 'webRouter');

$packager->hasMiddlewareAliases([
    'custom.alias' => \Vendor\Package\Http\Middleware\CustomMiddleware::class,
    'auth.custom' => \Vendor\Package\Http\Middleware\CustomAuthMiddleware::class,
]);

Route::get('/example', fn () => 'Hello')->middleware('custom.alias');

$packager->hasMiddlewareGroups([
    'web' => [
        \Vendor\Package\Http\Middleware\WebMiddleware::class,
    ],
    'api' => [
        \Vendor\Package\Http\Middleware\ApiMiddleware::class,
        \Vendor\Package\Http\Middleware\RateLimitMiddleware::class,
    ],
]);

$packager->hasMiddlewareGlobals([
    \Vendor\Package\Http\Middleware\GlobalMiddleware::class,
    \Vendor\Package\Http\Middleware\SecurityMiddleware::class,
]);

$packager->hasMigrations();

$packager->hasMigrations();

$packager->hasMigrations([
    '../www/database/migrations/2023_01_01_000000_create_users_table.php',
    '../api/database/migrations/2023_01_01_000001_create_roles_table.php',
]);

$packager->hasMigrations(directory: 'custom-migrations');

$package->hasMigrations(
    ['2023_01_01_000000_create_users_table.php'],
    'userMigrations'
);

$packager->canLoadMigrations();

$packager->hasTranslations();

$packager->hasTranslations('custom-lang-directory');

$packager->hasCommands();

$packager->hasCommands(directory: 'custom-commands');

$packager->hasCommand('\Vendor\Package\Commands\CustomCommand::class');

$packager->hasCommands([
    '\Vendor\Package\Commands\CustomCommand::class',
    '\Vendor\Package\Commands\OtherCommand::class',
]);

$packager->hasViews();

$packager->hasViews('custom-views');

$packager->hasViews(
    viewsPath: 'my-views', 
    directory: '../resources/my-views'
);

$packager->hasViews(__DIR__.'/../resources/views/admin', 'admin', 'mypackage-admin');

$packager->hasComponents(
    prefix: 'nyon',
    components: [
        'data-table' => DataTable::class,
        'modal' => Modal::class,
        Sidebar::class,
    ]
);

$packager->hasComponent('nyon', Alert::class, 'custom-alert');

$packager->hasComponentNamespaces(
    namespaces: [
        'nyon' => 'App\View\Components\Alert',
        'admin' => 'App\View\Components\Modal',
    ]
);

$packager->hasComponentNamespace('nyon', 'App\View\Components\Alert');

$packager
    ->hasViewComposer(
        views: 'nyon',
        composers: fn($view) => $view->with('test', 'test-value')
    )->hasViewComposer(
        views: ['viewName', 'anotherViewName'],
        composers: MyViewComposer::class
    );

$packager->hasViewComposer('*', function ($view) {
    $view->with('globalData', 'available-everywhere');
});

$packager->hasSharedDataForAllViews(['key' => 'value', 'user' => 'john']);

$packager->hasAssets();

$packager->hasAssets('public');

$packager->hasProvider('../stubs/MyProvider.stub');

$packager->hasProvider('../stubs/MyProvider.stub')
    ->hasProvider('../stubs/MyOtherProvider.stub');

$packager->hasProviders([
    '../stubs/MyProvider.stub',
    '../stubs/MyOtherProvider.stub',
]);

$packager->hasInstallCommand();

$packager->hasInstallCommand(function (InstallCommand $command) {
    $command->publishConfig()
        ->publishMigrations()
        ->publishAssets()
        ->publishViews();
});

$packager
    // Custom command name
    ->installCommandName('setup')  // Creates package:setup instead of package:install
    
    // Hide command from artisan list
    ->installCommandHidden(true)
    
    // Auto-install when package loads
    ->installOnRun(true)
    
    // Install only in specific environments
    ->installOnRunInEnvironment(['local', 'testing'])
    ->installOnRunInLocal()
    ->installOnRunInProduction();

// Quick install (config, migrations, assets)
$packager->hasQuickInstall();

// Full install (everything)
$packager->hasFullInstall();

// Minimal install (config only)
$packager->hasMinimalInstall();

// Development install (config, migrations, views, assets, routes in local only)
$packager->hasDevInstall();

$packager->hasInstallCommand(function (InstallCommand $command) {
    $command
        ->publishConfig()
        ->publishMigrations()
        ->publishAssets()
        ->publishForEnvironment(['local'], 'routes')
        ->publishForProduction('config')
        ->beforeInstallation(function ($command) {
            $command->info('Starting installation...');
        })
        ->afterInstallation(function ($command) {
            $command->info('Installation completed!');
            $command->call('migrate');
        })
        ->askToStarRepoOnGitHub('https://github.com/your/repo');
});

$command
    ->publishIf($someCondition, 'config', 'migrations')
    ->publishUnless($otherCondition, 'routes')
    ->publishForEnvironment(['local', 'testing'], 'routes')
    ->publishForProduction('config')
    ->publishForLocal('assets');

$packager->hasAbout();

$packager->hasVersion('1.0.0');

public function aboutData(): array
{
    return [
        'Repository' => 'https://github.com/your/package',
        'Author' => 'Your Name',
        'License' => 'MIT',
        'Documentation' => 'https://docs.example.com',
    ];
}

database/migrations/
├── 2025_01_01_000000_create_users_table.php
└── 2025_01_01_000001_create_roles_table.php

database/migrations/
├── create_posts_table.php
└── create_comments_table.php

database/migrations/
├── 2025_01_01_000000_create_users_table.php   ← keeps original timestamp
├── create_posts_table.php                      ← gets timestamp on publish
└── create_comments_table.php                   ← gets timestamp on publish
bash
php artisan vendor:publish
bash
# Publish specific resources
php artisan vendor:publish --tag=my-package::config
php artisan vendor:publish --tag=my-package::migrations
php artisan vendor:publish --tag=my-package::assets

# Publish with force (overwrite existing files)
php artisan vendor:publish --tag=my-package::config --force