Development Tip

Laravel 5에서 모듈 식 앱을 구성하는 방법은 무엇입니까?

yourdevel 2020. 11. 15. 11:50
반응형

Laravel 5에서 모듈 식 앱을 구성하는 방법은 무엇입니까?


응용 프로그램을 모듈로 나누고 싶습니다. 예를 들어, 기본 로그인 기능, 앱 레이아웃 / 포맷 (CSS 등), 사용자 관리 및 일기를 포함하는 "핵심"모듈이 있습니다.

나중에 응용 프로그램에서 쉽게 추가하거나 제거 할 수있는 연락처 관리자와 같은 다른 모듈을 만들 수 있습니다.

어떤 모듈이 있는지 확인하고 해당 모듈에 대한 링크를 표시 / 숨기기위한 로직이 앱 탐색에 있습니다.

디렉토리 구조, 네임 스페이스 및 기타 필요한 측면에서 어떻게이 작업을 수행 할 수 있습니까?


creolab / laravel-modules를보고 있지만 Laravel 4 용이라고 나와 있습니다. 5에서도 똑같은 방식으로 사용할 수 있습니까?

문서에는 각 모듈 디렉토리 내에 모델, 컨트롤러 및 뷰를 배치하라는 내용이 있지만 이것이 경로와 어떻게 작동합니까? 이상적으로는 각 모듈에 자체 routes.php 파일이 있기를 바랍니다. 이 모든 것이 httpresources디렉토리 의 항목 어떻게 작동 합니까?


나는 다음과 같은 것을 생각하고 있었다.

모듈 아이디어

그러나 나는 그것을 어떻게 작동시킬 것인지 전혀 모른다.


여기에서 튜토리얼을 시도했습니다.

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

추가 라이브러리 등없이 순수한 Laravel 5 만 있으면됩니다.

오류 메시지와 함께 벽돌 벽에 부딪힌 것 같습니다.

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

다음에 관하여 :

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

}

이 문제의 원인은 무엇이며 어떻게 해결할 수 있습니까?


이제 이것에 대해 좀 더 생각했습니다. 내 패키지 / 모듈 경로 및보기가 작동 중입니다.

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

}

마지막 질문이 있습니다. 방법이 loadViewsFrom()작동 하는 방식 과 마찬가지로 패키지 내부에서 모든 컨트롤러를 어떻게로드 할까요?


나는 그것을 모두 알아 낸 것 같다.

다른 초보자에게 도움이 될 수 있도록 여기에 게시하겠습니다. 네임 스페이스를 올바르게 설정하는 것뿐입니다.

내 composer.json에는 다음이 있습니다.

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

내 디렉토리와 파일은 다음과 같이 끝났습니다.

여기에 이미지 설명 입력

네임 스페이스를 지정하는 그룹에서 해당 모듈의 컨트롤러를 래핑하여 코어 모듈 router.php를 작동하게했습니다.

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

패키지에 대한 모델을 만들 때 네임 스페이스를 올바르게 가져 오는 비슷한 경우가 될 것이라고 상상합니다.

모든 도움과 인내심에 감사드립니다!


해결책:

1 단계 : "app /"내에 "Modules"폴더 생성


2 단계 : 모듈 폴더에서 모듈 생성 (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)

마찬가지로 여러 모듈을 만들 수 있습니다.

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

3 단계 : "Modules /"폴더 안에 ModulesServiceProvider.php 생성


4 단계 : 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 <query@programmerlab.com>
 * @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 : 'config / app.php'파일에 다음 줄 추가

App\Modules\ModulesServiceProvider::class,

Step6 : 'config'폴더 안에 module.php 파일 생성

Step7 : module.php 안에 다음 코드 추가 (경로 =>“config / module.php”)

<?php

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

참고 : 생성 한 모듈 이름을 추가 할 수 있습니다. 여기에 모듈이 있습니다.

Step8 :이 명령 실행

composer dump-autoload

조금 늦었지만 향후 프로젝트에서 모듈을 사용하려면 모듈 생성기를 작성했습니다. 모듈을 생성합니다. php artisan make:module name또한 app/Modules폴더에 일부 모듈을 놓을 수 있으며 사용 / 작업 할 준비가되었습니다. 구경하다. 시간 절약;)

l5- 모듈 식


탁구 실험실을 사용할 수도 있습니다.

문서 여기 .

여기에 예가 있습니다.

프로세스를 설치하고 확인할 수 있습니다.

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.


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.

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 <query@programmerlab.com>
* @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() {}

}

pingpong/modules is 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.

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

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

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

And then run composer install to fetch the package.

To create a new module you can simply run :

php artisan module:make <module-name>

-필수입니다. 모듈 이름이 생성됩니다. 새 모듈 만들기

php artisan module:make Blog

여러 모듈 만들기

php artisan module:make Blog User Auth

추가 방문 : https://github.com/pingpong-labs/modules

참고 URL : https://stackoverflow.com/questions/28485690/how-to-structure-a-modular-app-in-laravel-5

반응형