Configure files in a package for shared components in Laravel

Introduction

I have a huge project that contains many Laravel projects that are responsible for different things. Projects partially use the same database (users, permissions, roles, logs ...) and, for example, there is one project that is used to process user data and permissions for all other projects.

So, in this case, the projects had duplicate models (User, Permission, Role). I solved this by creating an independent package that will be included as a Composer package for all projects that use these models.

Problem

My question is about configuring the necessary packages. For example, now I use the Spatie permission package to handle permissions and roles. Each of my projects has the same configuration changes in these packages.

  • Is there a way to handle these configurations in my shared package too?
  • Can one package override another configuration file?
  • How does Laravel actually cope with such a situation that the necessary packages contain files with the same name?
+5
source share
1 answer

Create Shared Service

You can create a package, and all your projects will register it as a dependency. Use this package to override all dependency configuration files.

In your shared service, you need to create a service provider for each of the service providers you want to override. Extend the dependency service provider and use the register method to load your own configuration file, not the dependency configuration file.

For instance:

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

If you use Laravel 5.5 or higher, you may need to opt out of automatically detecting packages for each of your dependencies in order to prevent the use of dependency service providers. Register your service providers in composer.json instead.

If you use Laravel 5.4 or lower, or if you override a service provider that does not use automatic discovery, remove the service providers of your dependencies from your config/app.php and add your own.

+2
source

Source: https://habr.com/ru/post/1274429/


All Articles