How to make controllers, models, views outside app folder in Laravel 4?

时光毁灭记忆、已成空白 提交于 2019-12-08 06:21:13

问题


I want to make a structure folder like this:

root/
  admin/
     controllers/
       AdminController.php
       BaseController.php
     models/
     views/
  app/
  ... etc

I updated composer.json:

"autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "admin/controllers",
            "admin/models",
            "admin/views",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },

And then run 2 commands: composer dump-autoload, php artisan dump-autoload and create a route: Route::get('/admin', 'AdminController@showWelcome');. But when I hit http://localhost/laravel/admin, I get an error. Anyone can show me how to fix this problem?


回答1:


Register a PSR-4 command in your composer.json like this

"psr-4" : {
        "root\\" : "YOUR_ROOT_FOLDER"
    }

Then in root/admin/controllers/AdminController.php you have to namespace the class and call any class that you extend or use like this

<?php namespace Root\Admin\Controllers;

use BaseController;

class AdminControllers extends BaseController {
}

Don't forget to run composer dump-autoload

EDIT: to be able to use the views in other folders other than app folder you'll have to register the views, I usually do it via a service provider like this

In root/admin create a folder called Providers

Inside it create a file AdminServiceProvider.php and write in this

<?php namespace Root\Admin\Providers;

use Illuminate\Support\ServiceProvider;

class AdminServiceProvider extends ServiceProvider {

    public function register() {
        //
    }

    public function boot() {
       \View::addNamespace('admin', __DIR__ . '/../views/');
    }
}

Now go into app/config/app.php and scroll down to providers and before the array ends add this Root\Admin\Providers\AdminServiceProvider

Save it and run composer dump-autoload

Now in int Root namespace Controllers you can call any view like this

return View::make('admin::NAME_OF_YOUR_VIEW');

or if you need to access the view from inside a folder

return View::make('admin::NAME_OF_YOUR_FOLDER.NAME_OF_YOUR_VIEW');


来源:https://stackoverflow.com/questions/29725760/how-to-make-controllers-models-views-outside-app-folder-in-laravel-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!