定制 eubourne/laravel-plugins 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

eubourne/laravel-plugins

Composer 安装命令:

composer require eubourne/laravel-plugins

包简介

Module support for Laravel projects for better code organization.

关键字:

README 文档

README

Laravel Plugins

Laravel plugins

Laravel Plugins is a package designed to organize Laravel code into modules, allowing for better separation of features and easier code management. This package helps you structure your project into logical modules, such as Cart, Catalog, Blog, etc., where each module contains its own service providers, routes, and other resources.

Features

  • Organize project code by modules: Group related code in dedicated module folders, improving structure and maintainability.
  • Automatic module detection: The package automatically scans the modules directory for defined modules.
  • Module-specific resource loading: Each module can contain service providers, routes, translations, and channels that are loaded individually.
  • Module structure: Modules are self-contained and follow a predictable directory structure for easier development and scaling.

Installation

To install the package, run:

composer require eubourne/laravel-plugins

This package makes use of Laravels package auto-discovery mechanism, so you don't have to manually register its service provider.

Run the following artisan command to publish configuration file:

php artisan plugin:install

It will create config/plugins.php file with reasonable defaults.

Instruct composer autoload in composer.json where to look for your module files:

"autoload": {
    "psr-4": {
        "Modules\\": "modules/",
    }
}

NOTE:

The path should match the value specified in the groups.*.path section of your config/plugins.php file. If you have multiple groups, you need to add a separate psr-4 entry in package.json for each group.

After updating the composer.json, run:

composer dump-autoload

Basic Usage

Creating a Module

  1. Add a modules directory: In the root of your project, create a modules folder if it doesn’t already exist.
  2. Create a module folder: For each module, create a directory under modules (e.g., Cart, Catalog, Blog, etc.).
  3. Define the module: Inside each module folder, create a <ModuleName>Module.php file. This file should extend EuBourne\LaravelPlugins\Plugin class, enabling it to be registered by the package.

Directory Structure

A module typically follows this structure:

modules/
├── Cart/
│   ├── Providers/                      # Folder for service providers
│   │   └── ServiceProvider.php
│   ├── Routes/
│   │   ├── web.php                     # Web routes for the module
│   │   ├── api.php                     # API routes for the module
│   │   └── channels.php                # Broadcasting channels
│   ├── Lang/                           # Folder for translations
│   │   └── en/
│   │       └── messages.php
│   └── CartModule.php                  # Main module definition file
└── Catalog/
    ├── Providers/
    ├── Routes/
    ├── Lang/
    └── CatalogModule.php

You can customize the default suffix for plugin descriptor files to better suit your project needs. For example, instead of using <ModuleName>Module.php, you can switch to <ModuleName>Widget.php. To achieve this, update the suffix parameter in the config/plugins.php file. Additionally, if you have multiple groups, you can specify a unique suffix for each group using the groups.*.suffix parameter. This flexibility allows you to tailor the naming conventions to your application's structure.

Registering Module Resources

Service Providers

Each module can register a main service provider by creating a Providers/ServiceProvider.php file inside the module directory. The package automatically registers this provider if it’s found.

  • Additional Service Providers: You can specify more service providers from the main service provider. For convenience, you can inherit module service provider from EuBourne\LaravelPlugins\BaseServiceProvider and override its $providers property with an array of service providers to register.

    namespace Modules\Blog\Providers;
    
    use EuBourne\LaravelPlugins\BaseServiceProvider;
    
    class ServiceProvider extends BaseServiceProvider
    {
      protected array $providers = [
        BlogLoggingServiceProvider::class,
        // ...
      ]
    }

    This way both Modules\Blog\Providers\ServiceProvider and Modules\Blog\Providers\BlogLoggingServiceProvider will be registered.

  • Override Default Providers: To replace auto-discovered providers with a fixed list, override the $providers array in <ModuleName>Module.php.

    namespace Modules\Blog;
    
    class BlogModule extends EuBourne\LaravelPlugins\Plugin
    {
      protected array $providers = [
        \Modules\Blog\Providers\BlogLoggingServiceProvider::class,
        \Modules\Blog\Providers\ServiceProvider::class,
      ];
    }

    NOTE:

    All module service providers should extend Illuminate\Support\ServiceProvider.

Routes

By default, the package registers routes and applies specific middleware based on file names:

  • Web routes: The package loads routes from web.php and applies the web middleware.
  • API routes: All routes defined in files that match api*.php filename pattern (i.e.: api.php, api_v1.php, api_admin.php, etc.) will be loaded with the api middleware.

To configure additional route file names:

  1. Edit the config/plugins.php file.
  2. Update the routes section to add or modify route files. For example:
'routes' => [
    'web' => [
        'filename' => 'web*.php' // Allows `web.php`, `web_admin.php`, etc.
    ],
    'api' => [
        'filename' => 'api*.php' // Allows `api.php`, `api_v1.php`, etc.
    ]
]

Event Discovery

The package automatically discovers events and listeners from the Listeners directory in each module. It works the same way as original Laravel event discovery, where the package scans the Listeners directory for event listeners and registers them.

If you need to customize the event discovery paths, you can do so by overriding the $listeners property of the module:

class Blog extends Plugin
{
    protected array $listeners = [
        __DIR__ . '/MyListeners'
    ];
}

To disable event discovery for a specific module, set the $listeners property to an empty array:

class Blog extends Plugin
{
    protected array $listeners = [];
}

Multiple Module Groups

You can define multiple module groups in the groups section of the configuration file. Each group may have its own root directory and unique route configurations.

Example configuration:

'groups' => [
    'modules' => [
        'path' => 'modules', // modules root directory
        'routes' => [
            'web' => [
                'filename' => 'web*.php'
            ],
            'api' => [
                'filename' => 'api*.php'
            ]
        ]
    ],
    'widgets' => [
        'path' => 'widgets',
        'routes' => [
            'api' => [
                'filename' => 'api_v*.php' // Specific to widgets group
            ]
        ]
    ]
]

In this example:

  • modules is the main group for primary modules.
  • widgets is a secondary group with its own routing configuration. Routes like api_v1.php and api_v2.php are loaded only within widgets.

Schedule Tasks

Often modules require scheduled tasks to run at specific intervals. To define scheduled tasks for a module, you can use the schedule method in the module service provider:

namespace Modules\Blog\Providers;

use Illuminate\Console\Scheduling\Schedule;
use EuBourne\LaravelPlugins\BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    public function (Schedule $schedule): void
    {
        $schedule->command('blog:clear')->daily();
    }
}

Example Module Definition

Here’s a sample BlogModule.php for the Blog module:

namespace Modules\Blog;

use EuBourne\LaravelPlugins\Plugin;

class BlogModule extends Plugin
{
}

Blog module service provider, placed in modules/Blog/Providers:

namespace Modules\Home\Providers;

use EuBourne\LaravelPlugins\BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    public function register(): void
    {
        // Register services
    }

    public function boot(): void
    {
        // Load resources
    }
}

Accessing Plugin Data

You can access plugin data using the PluginManager, which can be retrieved from the service container:

/**
 * Retrieve the PluginManager instance.
 *
 * @var \EuBourne\LaravelPlugins\PluginManager $manager
 */
$manager = app('plugin.manager');

/**
 * Get a list of all registered plugin keys.
 *
 * @var array $keys
 */
$keys = $manager->getKeys();

/**
 * Retrieve data for a specific plugin as an array.
 *
 * @var array $blogPluginData
 */ 
$blogPluginData = $manager->getPluginData('modules.blog');

/**
 * Retrieve a specific field value from a plugin's data.
 *
 * @var mixed $value
 */
$value = $manager->getFromPlugin('modules.blog', 'className');

/**
 * Retrieve the Plugin instance for a specific plugin.
 *
 * @var \EuBourne\LaravelPlugins\Plugin $plugin
 */
$plugin = $manager->getPlugin('modules.blog');

Optimization

Discovering modules on each request may impact performance due to file scan and read operations. To enhance performance, cache module discovery with the following command:

php artisan plugin:cache

To clear the cached module data and reset module discovery, run:

php artisan plugin:clear

The package also supports standard Laravel optimization commands:

php artisan optimize
php artisan optimize:clear

For information about discovered modules, two commands are available:

# Displays a list of all discovered plugins
php artisan plugin:list

# Shows details for a specific plugin
php artisan plugin {plugin_key}

License

This package is open-source and available for free under the MIT license.

Contributing

Feel free to submit issues or pull requests to help improve this package.

Contact

For more information or support, please reach out via GitHub or email.

eubourne/laravel-plugins 适用场景与选型建议

eubourne/laravel-plugins 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 16 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 11 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 eubourne/laravel-plugins 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 eubourne/laravel-plugins 我们能提供哪些服务?
定制开发 / 二次开发

基于 eubourne/laravel-plugins 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 16
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 17
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-11-14