Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Config files in package for shared components in Laravel

Introduction

I have a huge project which contains many Laravel projects that are responsible for different things. The projects partially share same database (users, permissions, roles, logs...) and for example there is one project which is used to handle user data and permissions for all another projects.

So in this case there was for example duplicated models in the projects (User, Permission, Role). I solved it by building independent package to be included as a Composer package to all projects that share those models.

Problem

My question is about required packages' configuration. For example, now I'm using Spatie's Permission package to handle permissions and roles. Each of my projects share the same configuration changes in those packages.

  • Is there any way to handle those configurations in my shared package, too?
  • Can one package override another's config file?
  • How Laravel actually handles that kind of situation that there is configuration files with same name in required packages?
like image 837
lingo Avatar asked Oct 29 '22 21:10

lingo


1 Answers

Create a Shared Service

You can create a package and have all of your projects register it as a dependency. Use that package to override all of your dependencies configuration files.

In your shared service you will need to create a service provider for each of the service providers you wish to override. Extend your dependency's service provider and use the register method to load your own configuration file rather than that of your dependency's configuration file.

For example:

class SharedPermissionServiceProvider extends PermissionServiceProvider
{
    public function register()
    {
        if (isNotLumen()) {
            $this->mergeConfigFrom(
                __DIR__.'/../config/permission.php',
                'permission'
            );
        }

        $this->registerBladeExtensions();
    }
}

If you are using Laravel 5.5 or higher you may need to opt-out of package auto-discovery for each of your dependencies in order to prevent your dependencies' service providers from being used. Register your service providers in your composer.json instead.

If you are using Laravel 5.4 or lower, or if you are overriding a service provider that does not use auto-discovery, remove your dependencies' service providers from your config/app.php and add your own.

like image 178
Mathew Tinsley Avatar answered Nov 04 '22 15:11

Mathew Tinsley