How to Set in a Middleware a Variable Accessible in All My Application

How to set in a middleware a variable accessible in all my application?

You can use 'env' for that. So in your middleware you do this:

def call(env)
env['account'] = Account.find(1)
@app.call(env)
end

You can get the value by using 'request' in your app:

request.env['account']

And please don't use global variables or class attributes as some people suggest here. That's a sure way to get yourself into troubles and really is a bad habit.

Define a variable in a middleware available to the following ones

Beside features, there is another - a simpler in my opinion - solution: HttpContext.Items, as described here. According to the docs, it is especially designed to store data for the scope of a single request.

Your implementation would look like this:

// Set data:
context.Items["RequestInfo"] = requestInfo;

// Read data:
var requestInfo = (RequestInfo)context.Items["RequestInfo"];

If I set a variable in my middleware, how do I make that available to my views in my views.py?

If you want it available in your views, you can add anything you want to the request object as that's ultimately passed down to your views.

request.myvar = 'hello'

How to make variables of one file accessible along the entire application?

Use service architecture or dependency injection.

Service architecture Way:

Make a directory structure like this:

root (directory)
|
|-->app.js
|-->controllers (directory)
|-->services (directory)
|
|-> DatabaseService.js
|-> XYZService.js
|-> index.js

Now in your index.js file require the service classes and export the instances of those classes, like so:

var Database =  require('./DatabaseService')
var XYZ = require('./XYZService')

module.exports = {
database: new Database(),
xyz: new XYZ()
}

Now, require these services wherever you want in your code, like so:

// SomeController.js
var database = require('../services').database

...
// DO WHATEVER YOU WANT WITH 'database' variable
...

Dependency Injection Way:

I'm assuming you are using express routes. Do a dependency injection by wrapping your route-controller inside a lambda function, like so:

api.get('/user/:id', function (req, res) { // <-- wrapping 
var database = new Database()
return yourRouteController(req, res, database) // <-- Inject your database instance here
})

PS I personally prefer the Service way as it's more modular and readable.

How to declare global variables available to all Blade Files?

A recommended way of doing this is to add a middleware that you apply to all the routes that you want to affect.

Middleware

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;

class GlobalVariablesMiddleware
{
$myVariable = "Value For Everyone";
View::share(['globalValue' => $myVariable]);
}

Add it to your kernel.php in the Http folder

protected $routeMiddleware = [
...
'myMiddleware' => \App\Http\Middleware\ GlobalVariablesMiddleware::class,
];

Once this is setup, you can easily apply it to individual routes or grouped ones to achieve what you are looking for

// Routes that will have the middleware    
Route::middleware(['myMiddleware'])->group(function () {

// My first route that will have the global value
Route::resource('/profile', App\Http\Controllers\ProfileController::class);

// My second route that will have the global value
Route::resource('/posts', App\Http\Controllers\PostController::class);
});

By doing it this way, you can easily control the data in the future if you would chose not to have the data global.

How to create global variables accessible in all views using Express / Node.JS?

After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals and then a bit farther down res.locals held the answers I needed.

I discovered for myself that the function app.locals takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.

So for my case in my app.js what I did was add:

app.locals({
site: {
title: 'ExpressBootstrapEJS',
description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
},
author: {
name: 'Cory Gross',
contact: 'CoryG89@gmail.com'
}
});

Then all of these variables are accessible in my views as site.title, site.description, author.name, author.contact.

I could also define local variables for each response to a request with res.locals, or simply pass variables like the page's title in as the optionsparameter in the render call.

EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals for each response and then call next. This middleware function will need to be placed above any other middleware which needs to use these locals.

EDIT: Another difference between declaring locals via app.locals and res.locals is that with app.locals the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals unless the value depends on the request req variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals.

Passing variables to the next middleware using next() in Express.js

Attach your variable to the res.locals object, not req.

Instead of

req.somevariable = variable1;

Have:

res.locals.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.



Related Topics



Leave a reply



Submit