如何处理laravel模块化应用程序中的路由

时间:2016-06-03 07:46:50

标签: php laravel module routes

我知道模块中的路由有问题/答案。但我已经尝试了所有这些,但我无法解决任何问题。

让我展示一下我做了什么。

我的文件夹结构

enter image description here

我的ModuleServiceProvider.php

namespace App\Modules;

class ModulesServiceProvider extends \Illuminate\Support\ServiceProvider
{
    /**
     * Will make sure that the required modules have been fully loaded
     * @return void
     */

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

我的BlogServiceProvider.php

namespace App\Modules\Blog;

class BlogServiceProvider extends \App\Modules\ModulesServiceProvider {

    public function register()
    {
        parent::register('Blog');
    }

    public function boot()
    {
        parent::boot('Blog');
    }
}

在app \ config \ app.php

'App\Modules\Blog\BlogServiceProvider', //在providers数组中添加

在app \ config

module.php已创建

return  [
    'modules' => [
       'Blog',
    ]
];

在composer.json

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

一切似乎都很完美,但我被困在路线中。

在我的app \ Modules \ Blog \ routes.php

    Route::group(['namespace' => array('Modules\Blog')], function() {
      Route::get('/',['as' => 'home', 'uses' => 'PostController@index']);
    });
Route::get('/', ['as' => 'home', 'uses' => 'App\Modules\Blog\Controllers\PostController@index']);

我得到的PostController不存在错误

我的控制器命名空间

 namespace App\Modules\Blog\Controllers;

我在两条路线上都收到了这个错误。我是否指定控制器路径。请帮忙。如何在模块化应用程序中路由。

5 个答案:

答案 0 :(得分:0)

尝试将路由组中的命名空间从['namespace' => array('Modules\Blog')]更改为['namespace' => 'App\Modules\Blog\Controllers'],看看它是否有效。

答案 1 :(得分:0)

1 编辑您的composer.json文件并将您的prs-4自动加载更正为:

 "psr-4": {
        "App\\": "app/",
        "Modules\\": "app/Modules/"
  }

2 删除“App”后更新文件的命名空间 并且 3 执行composer dump-autoload

答案 2 :(得分:0)

转到RouteServiceProvider上的map方法。您可以根据命名空间告诉laravel加载路由。

/**
 * Aspect applying the annotation {@link LogDuration} to where ever it has been added, see {@link #logDuration(ProceedingJoinPoint, LogDuration)}.  
 */
@Configurable
@Aspect
public class LogDurationAspect {

    private static final Logger LOGGER = LogManager.getLogger( LogDurationAspect.class );

    @Autowired
    private TimeMeasurer timeMeasurer;// = new TimeMeasurer();

    public LogDurationAspect() {
    }

    /** For any method with @LogDuration, no matter what the return type, name, or arguments are, call this method to log how long it takes. */ 
    @Around("@annotation(annotation)")
    public Object logDuration( ProceedingJoinPoint joinPoint , LogDuration annotation ) throws Throwable {

        System.out.println( timeMeasurer );

        final long startTime = timeMeasurer.now();
        try{
            final Object result = joinPoint.proceed();

            final long duration = timeMeasurer.timeSince( startTime );

            LOGGER.info( String.format( "%s returned %s took %d ms %.3f s" , annotation.value() , result , duration , 0.001 * duration ) );

            return result;
        }
        catch ( Throwable t){
            final long duration = timeMeasurer.timeSince( startTime );
            LOGGER.error( String.format( "%s took %d ms %.3f s" , annotation.value() , duration , 0.001 * duration ) , t);
            throw t;
        }
    }
}

/**
 * Simple annotation which will log the duration of a method via {@link LogDurationAspect#logDuration(org.aspectj.lang.ProceedingJoinPoint, LogDuration)}.
 */
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface LogDuration {
   String value();
}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = LogDurationAspectITests.TestConfiguration.class )
public class LogDurationAspectITests {

    @Autowired
    private TestListener underTest;

    @Rule 
    public OutputCapture outputCapture = new OutputCapture();

    @Autowired
    private TimeMeasurer timeMeasurer;

    @Test 
    public void annotationWorks() {

        // prove that scanning is working
        assertThat( timeMeasurer , is( notNullValue( ) ) );

        underTest.doIt( 1234 );

        assertThat( outputCapture.toString() , containsString ( "doIt 1 2 3 returned 2468 took") );
    }

    @SpringBootApplication
    @Configuration
    public static class TestConfiguration {
    }
}

@Component
public class TimeMeasurer{

    /** @return milliseconds between now and start.*/ 
    public long timeSince( long start ) {

        return now( ) - start;        
    }

    /** @return current time in milliseconds. */
    public long now( ) {

        return System.currentTimeMillis( );
    }

}

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.1.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

</dependencies>

答案 3 :(得分:0)

最后我得到了解决方案。我改变了ModuleServiceProvider

namespace App\Modules;

class ModulesServiceProvider extends \Illuminate\Support\ServiceProvider
{
    /**
     * Will make sure that the required modules have been fully loaded
     * @return void
     */

    public function boot()
    {

        if ($module = $this->getModule(func_get_args())) {
             require_once __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;
    }
}

我在require_once函数中替换了include而不是boot。它的工作。

在路上我正在给予

Route::get('new-post',['uses' => 'App\Modules\Blog\Controllers\PostController@create']);

希望它能帮助别人!!

答案 4 :(得分:-1)

看看这个包,