php 如何在 Laravel 5 中构建模块化应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28485690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:53:27  来源:igfitidea点击:

How to structure a modular app in Laravel 5?

phplaravellaravel-routinglaravel-5

提问by imperium2335

I would like to divide my application in modules. For instance, there would be a "core" modules that contains the basic login functionality, app layout/formatting (CSS etc), user management and a diary.

我想将我的应用程序分成模块。例如,会有一个包含基本登录功能、应用程序布局/格式(CSS 等)、用户管理和日记的“核心”模块。

Later on I may create other modules like a contact manager that can easily be added or removed from the application.

稍后我可能会创建其他模块,例如可以轻松地从应用程序中添加或删除的联系人管理器。

There would be some logic in the apps navigation for determining which modules are present and to show/hide the links to them.

应用程序导航中会有一些逻辑,用于确定存在哪些模块并显示/隐藏指向它们的链接。

How can I do this in terms of directory structure, namespaces and anything else that's needed?

我如何在目录结构、命名空间和其他任何需要的方面做到这一点?



I am looking at creolab/laravel-modules but it states that it is for Laravel 4. Can I still use it with 5 in exactly the same way?

我正在查看 creolab/laravel-modules,但它指出它适用于 Laravel 4。我仍然可以以完全相同的方式将它与 5 一起使用吗?

The documentation says to place models, controllers and views within each module directory, but how does this work with routes? Ideally I would like each module to have its own routes.php file. How will all of this work with the stuff in the httpand the resourcesdirectory?

文档说在每个模块目录中放置模型、控制器和视图,但这如何与路由一起工作?理想情况下,我希望每个模块都有自己的 routes.php 文件。所有这些将如何与httpresources目录中的内容一起使用?



I was thinking of something like this:

我在想这样的事情:

Module idea

模块理念

But I have no idea how I would get it to work.

但我不知道如何让它工作。



I have just tried the tutorial here:

我刚刚在这里尝试了教程:

http://creolab.hr/2013/05/modules-in-laravel-4/

http://creolab.hr/2013/05/modules-in-laravel-4/

With no extra libraries etc, just pure Laravel 5.

没有额外的库等,只有纯 Laravel 5。

I seem to have hit a brick wall with an error message:

我似乎撞到了一个带有错误消息的砖墙:

FatalErrorException in ServiceProvider.php line 16:
Call to undefined method Illuminate\Config\Repository::package()

Regarding the following:

关于以下内容:

<?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);
        }
    }

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

// Add routes
            $routes = app_path() . '/modules/' . $module . '/routes.php';
            if (file_exists($routes)) require $routes;
        }
    }

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

        return $module;
    }

}

What is causing this and how can I fix it?

这是什么原因造成的,我该如何解决?



Got my head around this a bit more now. Got my package/module routes and views working which is great:

现在我更了解这个了。让我的包/模块路由和视图正常工作,这很棒:

abstract class ServiceProvider extends \Illuminate\Support\ServiceProvider
{

    public function boot()
    {
        if ($module = $this->getModule(func_get_args())) {
            include __DIR__.'/'.$module.'/routes.php';
        }
        $this->loadViewsFrom(__DIR__.'/'.$module.'/Views', 'core');
    }

    public function register()
    {
        if ($module = $this->getModule(func_get_args())) {

        }
    }

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

        return $module;
    }

}

I have one last question, how would I load all my controllers from inside my package, much like how the loadViewsFrom()method works?

我还有最后一个问题,我将如何从包中加载所有控制器,就像该loadViewsFrom()方法的工作原理一样?

回答by imperium2335

I seem to have figured it all out.

我好像已经想通了。

I'll post it here in case it helps other beginners, it was just about getting the namespaces right.

我会把它贴在这里,以防它对其他初学者有帮助,这只是为了让命名空间正确。

In my composer.json I have:

在我的 composer.json 我有:

...
"autoload": {
    "classmap": [
        "database",
        "app/Modules"
    ],
    "psr-4": {
        "App\": "app/",
        "Modules\": "Modules/"
    }
}

My directory and files ended up like this:

我的目录和文件最终是这样的:

enter image description here

在此处输入图片说明

I got my Core module router.php to work by wrapping my controllers for that module in a group specifying the namespace:

我通过将该模块的控制器包装在指定命名空间的组中来使我的核心模块 router.php 工作:

Route::group(array('namespace' => 'Modules\Core'), function() {
    Route::get('/test', ['uses' => 'TestController@index']);
});

I imagine when I come to doing my models for the package it will be a similar case of getting the namespaces right.

我想当我开始为包做我的模型时,这将是一个类似的情况,即获得正确的命名空间。

Thanks for all your help and patience!

感谢您的帮助和耐心!

回答by Kundan roy

Solution:

解决方案:

Step1: Create Folder “Modules” inside “app/”

步骤1:在“app/”中创建文件夹“Modules”



Step2: In Modules folder create your Module (Module1( suppose admin Module))

步骤 2:在 Modules 文件夹中创建您的模块(Module1(假设管理模块))

 Inside admin module : create the following folder 

 1. Controllers  (here will your controller files)
 2. Views  (here will your View files)
 3. Models  (here will your Model files)
 4. routes.php (here will your route code in this file)

Similarly, you can create multiple modules

同样,您可以创建多个模块

Module2( suppose API )
-Controllers
-Views
-Models
-routes.php


Step3 : Create ModulesServiceProvider.php inside “Modules/” Folder

Step3:在“Modules/”文件夹中创建ModulesServiceProvider.php



Step4 : Paste following code inside ModulesServiceProvider.php

Step4 : 在 ModulesServiceProvider.php 中粘贴以下代码

<?php

namespace App\Modules;

/**
 * ServiceProvider
 *
 * The service provider for the modules. After being registered
 * it will make sure that each of the modules are properly loaded
 * i.e. with their routes, views etc.
 *
 * @author kundan Roy <[email protected]>
 * @package App\Modules
 */

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class ModulesServiceProvider extends ServiceProvider {

    /**
     * Will make sure that the required modules have been fully loaded
     *
     * @return void routeModule
     */
    public function boot() {
        // For each of the registered modules, include their routes and Views
        $modules=config("module.modules");

        while (list(,$module)=each($modules)) {

            // Load the routes for each of the modules

            if (file_exists(DIR.'/'.$module.'/routes.php')) {

                include DIR.'/'.$module.'/routes.php';
            }

            if (is_dir(DIR.'/'.$module.'/Views')) {
                $this->loadViewsFrom(DIR.'/'.$module.'/Views',$module);
            }
        }
    }

    public function register() { }

}

Step5 : Add following line inside ‘config/app.php' file

步骤 5:在 'config/app.php' 文件中添加以下行

App\Modules\ModulesServiceProvider::class,

Step6 : Create module.php file inside ‘config' folder

Step7 : Add following code inside module.php (path => “config/module.php”)

Step6:在'config'文件夹中创建module.php文件

Step7:在module.php中添加以下代码(路径=>“config/module.php”)

<?php

return [
    'modules'=>[
        'admin',
        'web',
        'api'
    ]
];

Note : You can add your module name whichever you have created. Here there are modules.

注意:您可以添加您创建的模块名称。这里有模块。

Step8 : Run this command

步骤 8:运行此命令

composer dump-autoload

回答by Gordon Freeman

A little late, but if you want to use modules in your future projects, i've written a module generator. It generates modules via php artisan make:module nameYou can also just drop some modules in the app/Modulesfolder and they are ready to use/work. Take a look. Save some time ;)

有点晚了,但是如果您想在以后的项目中使用模块,我已经编写了一个模块生成器。它通过生成模块php artisan make:module name您也可以将一些模块放在app/Modules文件夹中,它们就可以使用/工作了。看一看。节省一些时间;)

l5-modular

l5-模块化

回答by Jnanaranjan

You can also use pingpong-labs

你也可以使用乒乓实验室

documentations Here.

文档在这里

Here is an example.

这是一个例子。

You can just install and check the process.

您只需安装并检查该过程即可。

Note: I am not advertising. Just checked that cms built on Laravel with module support. So thought that might be helpful for you and others.

注意:我不是广告。刚刚检查了在 Laravel 上构建的具有模块支持的 cms。所以认为这可能对你和其他人有帮助。

回答by gabrielkolbe

Kundan roy: I liked your solution but I copied your code from StackOverflow, I had to change the quotes and semi-quotes to get it working - I think SOF replace these. Also changed Dir for base_path() to be more inline with Laravel's (new) format.

Kundan roy:我喜欢你的解决方案,但我从 StackOverflow 复制了你的代码,我不得不更改引号和半引号以使其正常工作 - 我认为 SOF 替换了这些。还更改了 base_path() 的 Dir 以更符合 Laravel 的(新)格式。

namespace App\Modules;

/**
* ServiceProvider
*
* The service provider for the modules. After being registered
* it will make sure that each of the modules are properly loaded
* i.e. with their routes, views etc.
*
* @author kundan Roy <[email protected]>
* @package App\Modules
*/

use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class ModulesServiceProvider extends ServiceProvider
{

/**
* Will make sure that the required modules have been fully loaded
* @return void routeModule
*/
   public function boot()
{
    // For each of the registered modules, include their routes and Views
    $modules = config("module.modules");

    while (list(,$module) = each($modules)) {

        // Load the routes for each of the modules
        if(file_exists(base_path('app/Modules/'.$module.'/routes.php'))) {
            include base_path('app/Modules/'.$module.'/routes.php');
        }

        // Load the views                                           
        if(is_dir(base_path('app/Modules/'.$module.'/Views'))) {
            $this->loadViewsFrom(base_path('app/Modules/'.$module.'/Views'), $module);
        }
    }
}

public function register() {}

}

回答by Sagar Naliyapara

pingpong/modulesis a laravel package which created to manage your large laravel app using modules. Module is like a laravel package for easy structure, it have some views, controllers or models.

pingpong/modules是一个 laravel 包,用于使用模块管理大型 laravel 应用程序。模块就像一个 laravel 包,结构简单,它有一些视图、控制器或模型。

It's working in both Laravel 4 and Laravel 5.

它适用于 Laravel 4 和 Laravel 5。

To install through composer, simply put the following in your composer.jsonfile:

要通过 composer 安装,只需将以下内容放入您的composer.json文件中:

{
    "require": {
        "pingpong/modules": "~2.1"
    }
}

And then run composer installto fetch the package.

然后运行composer install以获取包。

To create a new module you can simply run :

要创建一个新模块,您只需运行:

php artisan module:make <module-name>

php artisan module:make <module-name>

- Required. The name of module will be created. Create a new module

- 必需的。将创建模块的名称。创建一个新模块

php artisan module:make Blog

php artisan module:make Blog

Create multiple modules

创建多个模块

php artisan module:make Blog User Auth

php artisan module:make Blog User Auth

for more visit: https://github.com/pingpong-labs/modules

更多访问:https: //github.com/pingpong-labs/modules