# Modules

Extract and modularize your code for maintainability. Essentially creates "mini-laravel" structures to organize your application.

# Installation

Simply install the package through Composer. From here the package will automatically register its service provider and Module facade.

composer require caffeinated/modules

# Config

To publish the config file, run the following:

php artisan vendor:publish --provider="Caffeinated\Modules\ModulesServiceProvider" --tag="config"

Below you will find the contents of the provided config file for reference.

<?php

return [

    /*
|--------------------------------------------------------------------------
| Default Location
|--------------------------------------------------------------------------
|
| This option controls the default module location that gets used while
| using this package. This location is used when another is not explicitly
| specified when exucuting a given module function or command.
|
*/ 'default_location' => 'app', /*
|--------------------------------------------------------------------------
| Locations
|--------------------------------------------------------------------------
|
| Here you may define all of the module locations for your application as
| well as their drivers and other configuration options. This gives you
| the flexibility to structure modules as you see fit in each location.
|
*/ 'locations' => [
'app' => [
'driver' => 'local',
'path' => app_path('Modules'),
'namespace' => 'App\\Modules\\',
'enabled' => true,
'provider' => 'ModuleServiceProvider',
'manifest' => 'module.json',
'mapping' => [ // Here you may configure the class mapping, effectivly
// customizing your generated default module structure. 'Config' => 'Config',
'Database/Factories' => 'Database/Factories',
'Database/Migrations' => 'Database/Migrations',
'Database/Seeds' => 'Database/Seeds',
'Http/Controllers' => 'Http/Controllers',
'Http/Middleware' => 'Http/Middleware',
'Providers' => 'Providers',
'Resources/Lang' => 'Resources/Lang',
'Resources/Views' => 'Resources/Views',
'Routes' => 'Routes'
],
],
], /*
|--------------------------------------------------------------------------
| Default Driver
|--------------------------------------------------------------------------
|
| Here you may specify the default module storage driver that should be
| used by the package. A "local" driver is available out of the box that
| uses the local filesystem to store and maintain module manifests.
|
*/ 'default_driver' => 'local', /*
|--------------------------------------------------------------------------
| Drivers
|--------------------------------------------------------------------------
|
| Here you may configure as many module drivers as you wish. Use the
| local driver class as a basis for creating your own. The possibilities
| are endless!
|
*/ 'drivers' => [
'local' => 'Caffeinated\Modules\Repositories\LocalRepository',
],
];

# Basic Usage

When it comes to larger applications, instead of mixing and matching your controllers, models, etc. across the various domains of your project, modules can group related logic together into a tidy "package". Out of the box, modules are stored in the app/Modules directory. Later on we'll go over how you can change this location or even add additional locations to store your modules.

# Creating Modules

Modules can be created by the use of the make:module Artisan command:

php artisan make:module Blog

This command will generate all the necessary files and folders to get you up and running quickly at app/Modules/Blog.

You'll notice that the structure of modules closely resemble the default Laravel folder structure. This is intentional and should feel immediately familiar to you. Nothing too scary here!

# Manifest

One of the important files that must be present at the root of every module, is the module's manifest file: module.json. This file contains the info and identification of your module. You may also use this to store module-specific settings if you wish. Let's look at the contents provided out of the box and go over each in detail:

{
"name": "Blog",
"slug": "blog",
"version": "1.0",
"description": "Only the best blog module in the world!",
}
Property Description
name * The human-readable name of your module.
slug * The slug of your module used to reference in commands and code.
version * The version of your module.
description * A simple description of your module.
order You may also optionally pass in the order in which your module is loaded. Defaults to 9001.

* These properties are required in every manifest.

Once you've made a change to a manifest file, you will need to re-optimize your module manifest cache. You can do this by running the following Artisan command:

php artisan module:optimize

# Service Providers

Just as the case with Laravel packages, service providers are the connection points between your module and Laravel. A service provider is responsible for binding things into Laravel's service container and information Laravel where to load module resources such as views, configuration, and localization files.

A ModuleServiceProvider and RouteServiceProvider is provided out of the box with some defaults configured for your module's localization, view, migration, configuration, factory, and route files. Feel free to modify these files or create your own service providers as needed.

You may generate a new provider via the make:module:provider command:

php artisan make:module:provider blog PublisherServiceProvider

NOTE

Be sure to register your custom service providers within your ModuleServiceProvider. Refer to Laravel's service provider documentation as needed.

# Migrations

We've extended Laravel's migrations system to make it easier to work with migrations for your modules. Particularly, you're able to run, rollback, reset, and refresh migrations for individual modules separate from your application (or other modules). This makes it super easy to work with modules during development.

# Generating Migrations

To create a module migration, use the make:module:migration Artisan command:

php artisan make:module:migration blog create_posts_table

The new migration will be placed in your defined migrations directory (by default this is Database/Migrations). Migrations follow the same workflow and structure as any other Laravel migration, so be sure to check out the documention on them here for reference.

# Running Migrations

To run all of your outstanding module migrations, execute the module:migrate Artisan command:

php artisan module:migrate

You may optionally specificy the exact module you'd like to run migrations against by passing through the slug:

php artisan module:migrate blog

Lastly, every module migrate command accepts the use of the --location flag to specify which module location to target.

# Rolling Back Migrations

To rollback the latest migration operation, you use the module:migrate:rollback command.

php artisan module:migrate:rollback

The rollback command also supports the step option to rollback a certain number of migrations:

php artisan module:migrate:rollback --step=5

You may also specify the module you wish to rollback, specifically:

php artisan module:migrate:rollback blog

The module:migrate:reset command will roll back all of your module migrations or the migrations of the module you pass through:

php artisan module:migrate:reset

php artisan module:migrate:reset blog

# Enabling Modules

Modules may be enabled either through the module:enable artisan command or through the facade with enable():

php artisan module:enable blog
Module::enable('blog');

# Disabling Modules

Modules may be disabled either through the module:disable artisan command or through the facade with disable():

php artisan module:disable blog
Module::disable('blog');

# Digging Deeper

# Locations

You may configure as many locations for your modules as necessary. For example, you may to split up your "core" modules from optional "add-on" modules.

The location configuration is found in the config/modules.php file under "locations". Here you may customize locations as needed. By default, the package is configured to store and reference modules from the app/Modules directory.

Each location may have its own configuration options on how you'd like to structure your modules:

Property Description
driver The module driver to use for this location.
path The root path where you wish to store modules for this location.
namespace The root namespace used when generating modules for this location.
enabled Whether or not modules are enabled by default or not in this location.
provider The master provider class name for modules in this location.
manifest The manifest filename for modules in this location. Must be a JSON file.
mapping The custom mapping of directories for modules in this location.

# Publishing Resources

Typically, you will need to publish your module's resources to the application's own directories. This will allow users of your module to easily override your default resources.

To publish your module's resources to the application, you may call the service provider's publishes method within the boot method of your service provider. The publishes method accepts an array of module paths and their desired publish locations. For example, to publish a config file for your blog module, you may do the following:

/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$this->publishes([
module_path('blog', 'config/blog.php') => config_path('blog.php'),
]);
}

# Provided Middleware

The bundled Identify Module middleware provides the means to pull and store module manifest information within the session on each page load. This provides the means to identify routes from specific modules.

# Register

Simply register as a route middleware with a short-hand key in your app/Http/Kernel.php file.

protected $routeMiddleware = [
...
'module' => \Caffeinated\Modules\Middleware\IdentifyModule::class,
];

# Usage

Now, you may simply use the middleware key in the route options array. The IdentifyModule middleware expects the slug of the module to be passed along in order to locate and load the relevant manifest information.

Route::group(['prefix' => 'blog', 'middleware' => ['module:blog']], function() {
Route::get('/', function() {
dd(
'This is the Blog module index page.',
session()->all()
);
});
});

# Results

If you dd() your session, you'll see that you have a new module array key with your module's manifest information available.

"This is the Blog module index page."
array:2 [▼
"_token" => "..."
"module" => array:6 [▼
"name" => "Blog"
"slug" => "blog"
"version" => "1.0"
"description" => "This is the description for the Blog module."
"enabled" => true
"order" => 9001
]
]

# Helpers

Caffeinated Modules includes a handful of global "helper" PHP functions. These are used by the package itself; however, you are free to use them in your own code if you find them convenient.



# modules

The modules function returns a collection of all modules and their accompanying manifest information.

$modules = modules();

# module_path

The module_path function returns the fully qualified path to the specified module's directory. You may also use the module_path function to generate a fully qualified path to a file relative to the module:

$path = module_path('blog');

$path = module_path('blog', 'Http/Controllers/BlogController.php');

If your module is not found within your configured default location, you may pass a third option to specify the location:

$path = module_path('blog', 'Http/Controllers/BlogController.php', 'add-on');

# module_class

The module_class function returns the full namespace path of the specified module and class.

$namespace = module_class('blog', 'Http\Controllers\BlogController');

If your module is not found within your configured default location, you may pass a third option to specify the location:

$namespace = module_class('blog', 'Http\Controllers\BlogController', 'add-on');

# API Reference


# all

Get all modules, returned as a Collection.

$modules = Module::all();

# slugs

Get all modules, returned as a Collection.

$modules = Module::slugs();

# where

Find a module based on a where clause, returns a Collection.

$blogModule = Module::where('slug', 'blog');

# sortBy

Get all modules sorted by key in ascending order, returned as a Collection.

$modules = Module::sortBy('name');

# sortByDesc

Get all modules sorted by key in descending order, returned as a Collection.

$modules = Module::sortByDesc('name');

# exists

Check if given module exists, returns a Boolean.

if (Module::exists('blog')) {
// Do something with it
}

# count

Returns a count of all modules.

$count = Module::count();

# getManifest

Get a module's manifest contents, returned as a Collection.

$manifest = Module::getManifest('blog');

# get

Returns the given module manifest property value. If a value is not found, you may define a default value as the second parameter.

$name = Module::get('blog::post_limit', 15);

# set

Set the given module manifest property value.

Module::get('blod::description', 'This is a fresh new description of the blog module.');

# enabled

Gets all enabled modules, returned as a Collection.

$enabled = Module::enabled();

# disabled

Gets all disabled modules, returned as a Collection.

$disabled = Module::disabled();

# isEnabled

Checks if the given module is enabled, returns a Boolean.

if (Module::isEnabled('blog')) {
// Do something
}

# isDisabled

Checks if the given module is disabled, returns a Boolean.

if (Module::isDisabled('blog')) {
// Do something
}

# enable

Enable the given module.

Module::enable('blog');

# disable

Disable the given module.

Module::disable('blog);

laravel学习:模块化caffeinated的更多相关文章

  1. laravel的模块化是如何实现的

    laravel的模块化是如何实现的 在laravel提供的官方文档上,有一个这样的名词 服务提供者,文档中介绍了它在laravel框架中的角色,以及如何使用它,但却没有讲明服务提供者的本质--它是为了 ...

  2. 【 js 模块加载 】深入学习模块化加载(node.js 模块源码)

    一.模块规范 说到模块化加载,就不得先说一说模块规范.模块规范是用来约束每个模块,让其必须按照一定的格式编写.AMD,CMD,CommonJS 是目前最常用的三种模块化书写规范.  1.AMD(Asy ...

  3. Laravel学习笔记(三)--在CentOS上配置Laravel

    在Laravel框架上开发了几天,不得不说,确实比较优雅,处理问题逻辑比较清楚.     今天打算在CentOS 7上配置一个Laravel,之前都是在本机上开发,打算实际配置一下.     1)系统 ...

  4. Laravel学习笔记之Session源码解析(上)

    说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助.Laravel在web middleware中定义了 ...

  5. 【 js 模块加载 】【源码学习】深入学习模块化加载(node.js 模块源码)

    文章提纲: 第一部分:介绍模块规范及之间区别 第二部分:以 node.js 实现模块化规范 源码,深入学习. 一.模块规范 说到模块化加载,就不得先说一说模块规范.模块规范是用来约束每个模块,让其必须 ...

  6. 《PHP框架Laravel学习》系列分享专栏

    <PHP框架Laravel学习>已整理成PDF文档,点击可直接下载至本地查阅https://www.webfalse.com/read/201735.html 文章 Laravel教程:l ...

  7. Laravel 学习 .env文件 getenv 获得环境变量的值

    Laravel 学习 .env文件 getenv 获得环境变量的值  我们还需要对应用的 .env 文件进行设置,为应用指定数据库名称 sample. .env . . . DB_DATABASE=s ...

  8. laravel学习之旅

    前言:之前写了二篇YII2.0的基本mvc操作,所以,打算laravel也来这一下 *安装现在一般都用composer安装,这里就不讲述了* 一.熟悉laravel (1)如果看到下面这个页面,就说明 ...

  9. laravel学习:主从读写分离配置的实现

    本篇文章给大家带来的内容是关于laravel学习:主从读写分离配置的实现,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 在DB的连接工厂中找到以下代码.../vendor/larav ...

  10. Laravel学习笔记之PHP反射(Reflection) (上)

    Laravel学习笔记之PHP反射(Reflection) (上) laravel php reflect 2.1k 次阅读  ·  读完需要 80 分钟 3 说明:Laravel中经常使用PHP的反 ...

随机推荐

  1. 什么叫强类型的DATASET ?对DATASET的操作处理?强类型DataSet的使用简明教程

    强类型DataSet,是指需要预先定义对应表的各个字段的属性和取值方式的数据集.对于所有这些属性都需要从DataSet, DataTable, DataRow继承,生成相应的用户自定义类.强类型的一个 ...

  2. sphinx索引部分源码续——过程:连接到CSphSource对应的sql数据源,通过fetch row取其中一行,然后解析出field,分词,获得wordhit,最后再加入到CSphSource的Hits里

    后面就是初始化一些存储结构,其中重点说下缓存出来的几个临时文件分别的作用.结尾时tmp0的存储的是被上锁的Index,有些Index正在被查询使用 故上锁.tmp1,即对应将来生成的spp文件,存储词 ...

  3. 【SCOI 2005】 最大子矩阵

    [题目链接] 点击打开链接 [算法] 动态规划 我们发现,M只有两种取值,1和2,那么,只需分类讨论即可 当M = 1时,其实这个问题就成了就最大连续子段和的问题,只不过要选K段而已 用f[i][j] ...

  4. rsync+inotify 实现实时同步

    inotify:这个可以监控文件系统中的添加,修改,删除,移动等事件 inotify的特性需要linux内核2.6.13以上的支持 [root@test1 inotify-tools-3.13]# u ...

  5. Java-Runoob-高级教程-实例-字符串:12. Java 实例 - 字符串优化

    ylbtech-Java-Runoob-高级教程-实例-字符串:12. Java 实例 - 字符串优化 1.返回顶部 1. Java 实例 - 字符串优化  Java 实例 以下实例演示了通过 Str ...

  6. linux上部署javaWeb项目

    将web项目打成war包,上传到Linux操作系统tomcat安装目录下的webapps下即可!

  7. 【137】Photoshop相关功能

    1. photoshop中怎样批处理操作 图文教程 来源:http://www.jb51.net/photoshop/57784.html 不知道大家有没有接触过PS里面的批处理呢,当我们要完成数百张 ...

  8. bzoj 1907: 树的路径覆盖【贪心+树形dp】

    我是在在做网络流最小路径覆盖的时候找到这道题的 然后发现是个贪心+树形dp \( f[i] \)表示在\( i \)为根的子树中最少有几条链,\( v[i] \) 表示在\( i \)为根的子树中\( ...

  9. Go语言Flag的简单示例

    flag 命令行参数解析,大家可能不太清楚是什么命令行参数解析,不要紧,我们来看看: 他就是干这个活的 func FlagTest1(){ var username string var userag ...

  10. 前缀和小结 By cellur925

    这篇主要是来介绍前缀和的QAQ. 前缀和有一维的和二维的,一维的很容易理解,高中数学必修5第二章数列给出了前n项和的概念,就是前缀和.一维的我们在这里简单说一句. 一维前缀和 预处理:在输入一个数列的 ...