NikDevPHP
5/16/2016 - 12:22 PM

Laravel Modules #laravel

Laravel Modules #laravel

<?php namespace App\Modules;

abstract class ServiceProvider extends \Illuminate\Support\ServiceProvider {

  public function boot()
  {
    if ($module = $this->getModule(func_get_args())) {
      $this->package('app/' . $module, $module, app_path() . '/modules/' . $module);

      // Add routes and filter if exists
      foreach(['routes', 'filters'] as $file) {
        if(file_exists(app_path(__DIR__."/modules/{$module}/{$file}.php"))) {
          include app_path(__DIR__."/modules/{$module}/{$file}.php");
        }
      }
    }
  }

  public function register()
  {
    if ($module = $this->getModule(func_get_args())) {
      $this->app['config']->package('app/' . $module, app_path() . '/modules/' . $module . '/config');
    }
  }

  public function getModule($args)
  {
    $module = (isset($args[0]) and is_string($args[0])) ? $args[0] : null;

    return $module;
  }
}

Laravel Modules

Add app/modules to classmap autoload on composer.json.

Example of ServiceProvider for Product Module on app/modules/product.

<?php namespace App\Modules\Product;
 
class ServiceProvider extends \App\Modules\ServiceProvider {
 
    public function register()
    {
        parent::register('product');
    }
 
    public function boot()
    {
        parent::boot('product');
    }
}

Add 'App\Modules\Product\ServiceProvider' to providers configuration on app/config/app.php.