jon
jon

Reputation: 1581

Should I use Laravel Middleware?

I have a Laravel app that requires getting some config vars that need to be used by most of my controllers. Therefore it seems like this would be the perfect time to use middleware. Is this the correct use of middleware? and if so, once the middleware gets the config vars, is it best practice to add these to the request object so they can be accessed by my controller? Thanks to any responders. J

Upvotes: 1

Views: 676

Answers (2)

felipsmartins
felipsmartins

Reputation: 13549

Not, definitely!

Actually (based on you've written), the best way to go is creating an application service and registering this service on Service Container - App\Providers\AppServiceProvider (in app/Providers/AppServiceProvider.php).

Something like this:

<?php
# The Config Service:

namespace App\Services;

/**
 * Config Manager
 */
class Config
{
    /** @var SomeDependency */
    protected $dependency;

    public function __construct(SomeDependency $dependency)
    {
        $this->dependency = $dependency;
    }

    public function getVar($var)
    {
        // ...
    }
}

In your Service Provider:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    //...

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

        $this->registerConfigManager();

    }

    public function registerConfigManager()
    {
        $this->app->singleton('config_service', function ($app) {
            return new \App\Services\Config(new \SomeNamespace\SomeDependency);
        });
    }

    //...
}

And now you can to access the service container via app(), like this:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class MyController extends Controller
{
    public function index(Request $request)
    {
        app('config_service')->getVar('key');
        //...
    }
}

Upvotes: 2

CarlosCarucce
CarlosCarucce

Reputation: 3569

IMO, middlewares are made for pre-processing requests, restrict user access, and other security related.

I would simply load the configuration in the main Controller class and use it in the extending controllers.

For example:

base controller

namespace App\Http\Controllers;

uses goes here ...;

class Controller extends BaseController
{
    protected $configs = [];

    public function __construct() {
        $this->loadConfigs();
    }

    protected function loadConfigs()
    {
        //read configuration files or tables in database 
        //and put the values into '$this->configs';
    }

}

user controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

class User extends Controller
{
    public function index()
    {
        echo $this->configs['toolbar.color']; //just an example
    }
}

Upvotes: 1

Related Questions