Home » Php » Thin Controllers in Laravel 4

Thin Controllers in Laravel 4

Posted by: admin November 29, 2017 Leave a comment

Questions:

I am trying to work out the ‘best’ way of structuring my controllers/models in a new Laravel 4 app.

Obviously I want to keep the controllers thin and lightweight. So I want to work with Repos/Services to separate things, however I don’t really know how to implement this in Laravel 4. Laravel 3 gave us some idea of how this should work, but no samples.

Has any one figured out the neatest way to do this, or have any sample code I could take a peek at?

Answers:

I agree on the fact that it isn’t very clear where to store these classes in Laravel 4.

A simple solution would be creating repositories/services folders in your main app/ folder and updating your main composer.json file to have them autoloaded:

{
    "require": {
        "laravel/framework": "4.0.*"
    },
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/tests/TestCase.php",
            "app/repositories",
            "app/services"
        ]
    },
    "minimum-stability": "dev"
}

Note: everytime you create a new class you have to run composer dump-autoload.

In case of repositories, you can have Laravel inject them into your controllers automatically. I find this a good screencast on this subject.

Questions:
Answers:

I found this collection of tutorials to be a great introduction on the proper place to store your custom service providers and other files that you want to inject into your project:

These tutorials come from this collection:

http://fideloper.com/tag/laravel-4

Questions:
Answers:

The first thing that I do when I get a fresh install of Laravel is:

  • Remove the “models” folder
  • Create a src folder
  • Under the src, create a Application folder (or the name of the app)
  • On Application folder, create Entities, Repositories, Services and Tests

So, in this case your namespace will be Application\Entities, Application\Repositories and Application\Services

In composer.json:

{
    "require": {
        "laravel/framework": "4.0.*"
    },
    "autoload": {
        "psr-0": {
            "Application": "app/src/"
        },
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/database/migrations",
        ]
    },
    "minimum-stability": "dev"
}

To each one of those you’ll need to create the classes and a service provider to bind a repository to an entity.

Here is a tutorial explaining how to create the repositories:

http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/

Anyway, I’m still looking for the best architecture. If anyone has a better idea, I’ll be glad to hear it!