Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Where to store global arrays data and constants?

I just started working with Laravel. I need to rewrite a whole system I made some years ago, using Laravel 4 as base framework. In my old system, I used to have a constant.php file with some constants declared, and a globals.php file which contained lots of array sets (for example, categories statuses, type of events, langs, etc.). By doing so, I could use something like

foreach ( $langs as $code => $domain ) {
    // Some stuff
}

anywhere in my app.

My question is, how can I store that info in the so called "laravel way". I tried using some sort of object to store this info, setting this as a service and creating for it a facade:

app/libraries/Project/Constants.php

namespace PJ;

class Constants {

    public static $langs = [
            'es' => 'www.domain.es',
            'en' => 'www.domain.us',
            'uk' => 'www.domain.uk',
            'br' => 'www.domain.br',
            'it' => 'www.domain.it',
            'de' => 'www.domain.de',
            'fr' => 'www.domain.fr'
        ];
}

app/libraries/Project/ConstantsServiceProvider.php

namespace PJ;

use Illuminate\Support\ServiceProvider;

class ConstantsServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->singleton('PJConstants', function() {
            return new Constants;
        });
    }
}

app/libraries/Project/ConstantsFacade.php

namespace PJ;

use Illuminate\Support\Facades\Facade;

class ConstantsFacade extends Facade {
    protected static function getFacadeAccessor() { 
        return 'PJConstants';
    }
}

composer.json

"psr-4": {
     "PJ\\": "app/libraries/Project"
},

and so I access that property as PJ\Constants::$langs.

This works, but I doubt it is the most efficient or correct way of doing it. I mean, is it the right way to "propagate" a variable by creating a whole Service Provider and facades and all such stuff? Or where should I put this data?

Thanks for any advice.

EDIT # 01

Data I want to pass to all controllers and views can be directly set in script, like in the example at the beginning of my post, but it can also be generated dynamically, from a database for example. This data could be a list of categories. I need them in all views to generate a navigation bar, but I also need them to define some routing patterns (like /category/subcategory/product), and also to parse some info in several controllers (Like get info from the category that holds X product).

My array is something like:

$categories = [
    1 => ['name' => 'General', 'parent' => 0, 'description' => 'Lorem ipsum...'],
    2 => ['name' => 'Nature', 'parent' => 0, 'description' => 'Lorem ipsum...'],
    3 => ['name' => 'World', 'parent' => 0, 'description' => 'Lorem ipsum...'],
    4 => ['name' => 'Animals', 'parent' => 2, 'description' => 'Lorem ipsum...']
]

Just as an example. Index is the id of the category, and the Value is info associated with the category.

I need this array, also, available in all Controllers and Views.

So, should I save it as a Config variable? How else could I store these data; what would be the best and semantically correct way?

like image 210
Marco Madueño Mejía Avatar asked Nov 10 '14 22:11

Marco Madueño Mejía


3 Answers

For most constants used globally across the application, storing them in config files is sufficient. It is also pretty simple

Create a new file in the app/config directory. Let's call it constants.php

In there you have to return an array of config values.

return [
    'langs' => [
        'es' => 'www.domain.es',
        'en' => 'www.domain.us'
        // etc
    ]
];

And you can access them as follows

Config::get('constants.langs');
// or if you want a specific one
Config::get('constants.langs.en');

And you can set them as well

Config::set('foo.bar', 'test');

Note that the values you set will not persist. They are only available for the current request.

Update

The config is probably not the right place to store information generated from the database. You could just use an Eloquent Model like:

class Category extends Eloquent {
    // db table 'categories' will be assumed
}

And query all categories

Category::all();

If the whole Model thing for some reason isn't working out you can start thinking about creating your own class and a facade. Or you could just create a class with all static variables and methods and then use it without the facade stuff.

like image 84
lukasgeiter Avatar answered Oct 08 '22 05:10

lukasgeiter


For Constants

Create constants.php file in the config directory:-

define('YOUR_DEFINED_CONST', 'Your defined constant value!');

return [

'your-returned-const' => 'Your returned constant value!'

];

You can use them like:-

echo YOUR_DEFINED_CONST . '<br>';

echo config('constants.your-returned-const');

For Static Arrays

Create static_arrays.php file in the config directory:-

class StaticArray
{

    public static $langs = [
        'es' => 'www.domain.es',
        'en' => 'www.domain.us',
        'uk' => 'www.domain.uk',
        'br' => 'www.domain.br',
        'it' => 'www.domain.it',
        'de' => 'www.domain.de',
        'fr' => 'www.domain.fr'
    ];

}

You can use it like:-

echo StaticArray::$langs['en'];

Note: Laravel includes all config files automatically, so no need of manual include :)

like image 30
Gagandeep Gambhir Avatar answered Oct 08 '22 05:10

Gagandeep Gambhir


Create common constants file in Laravel

app/constants.php

    define('YOUR_CONSTANT_VAR', 'VALUE');

    //EX
    define('COLOR_TWO', 'red');

composer.json add file location at autoload in composer.json

"autoload": {
    "files": [
        "app/constants.php"
    ]
}

Before this change can take effect, you must run the following command in Terminal to regenerate Laravel’s autoload files:

composer dump-autoload
like image 20
Parth kharecha Avatar answered Oct 08 '22 07:10

Parth kharecha