Multiple Projects using single laravel instance

前端 未结 2 465
被撕碎了的回忆
被撕碎了的回忆 2021-02-01 10:23

I am new to Laravel. As per my research on this framework I find it quite useful for my projects. However I am facing difficulty in customizing it to use a single instance of La

2条回答
  •  再見小時候
    2021-02-01 10:53

    Use Namespaces To Organize and Separate Things

    Create PSR-4 autoloading entries to separate your projects files by namespace:

    "psr-4": {
        "App\\Core\\": "app/App/Core",
        "App\\Main\\": "app/App/Main",
        "App\\Project1\\": "app/App/Project1",
        "App\\Project2\\": "app/App/Project2"
    },
    

    Everything common you put in Core, everything non-common in the related project files.

    Now you just have to create your files in theirs respective folders and namespace them:

    This is a BaseController in Core, used by all your controllers:

    This is a BaseController of the Main application using your Core Controller:

    And this is a HomeController of the Main application using your its Base Controller, as they are in the same namespace you don't even need to import the file:

    Every single class file in Laravel can be organized this way, even your views, so you can have those files:

    app/App/Core/Controllers/BaseController.php
    
    app/App/Main/Controllers/BaseController.php
    app/App/Main/Controllers/HomeController.php
    
    app/App/Project1/Controllers/BaseController.php
    app/App/Project1/Controllers/PostsController.php
    app/App/Project1/Controllers/UsersController.php
    
    app/App/Project1/Models/User.php
    app/App/Project1/Models/Post.php
    app/App/Project1/Models/Roles.php
    

    Then your routes could be separated (organized) and prefixed by namespace:

    Route::group(['prefix' => 'project1', 'namespace' => 'App\Project1\Controllers'], function()
    {
        Route::get('/', 'HomeController@index');
    
        Route::get('posts', 'PostsController@index']);
    });
    

    Giving those urls:

    http://yourdomain.com/project1
    http://yourdomain.com/project1/posts
    

    And pointing actions to those controller actions:

    App\Project1\Controllers\HomeController@index
    App\Project1\Controllers\PostsController@index  
    

提交回复
热议问题