Support the ongoing development of Laravel.io →
Requests Cache
Last updated 1 year ago.
0

Can you explain the purpose a little more? Can you use a cookie? It's difficult to answer without a proper use case.

You might want to take a look at Config in the docs. It might be the answer... Not really sure without understanding your issue properly.

Last updated 1 year ago.
0

Firstly when addressing a problem with globals in mind, always re-think your application architecture. Usually there is a better / easier way.

What are you trying to do? "Im generating a special random value"

Okay so that sounds like a service that your application needs. Just like Mail (for an emailing service) or Form (a service to help create HTML form elements easily).

So lets create a RandomValue service for you application

<?php namespace App\Services;


class RandomValue {

	public function generate($min = null, $max = null)
	{
		return mt_rand($min, $max);
	}
}

Nice and simple. you get the idea.

Now we need to register this service into the IOC (inversion of control) container so we can access it anywhere within our application.

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\RandomValue;

class RandomValueServiceProvider extends ServiceProvider {

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('RandomValue', function($app)
        {
            return new RandomValue(100,500);
        });
    }

}

But wait... if you look at closely you will notice that i used the following above:

$this->app->singleton(

this creates a "singleton" or simply it returns the same instance of the object we created right throughout your application. Remember that this will only live for one whole request cycle of your application...

Thus we achieve your original goal, in an elegant manner. YES we could have used cache, database persistence or any other number of ways. But essentially these all lack flexibility. In the future you may want to do more then generate a random value, you may want to perform calculations on this value... or store it in the database... well now you have a nice neat place to do this.

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Uriziel01 uriziel01 Joined 1 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.