user2354302
user2354302

Reputation: 1903

Laravel: Loading initial custom settings class

My aim is to fetch application concerned settings from a config file and load them to a DataSource and use it in the application. In the process of loading from the config file, I'd want to validate them and if they fail, Laravel should stop it's boot up. Sounds a bit a confusion, I guess. Hope the following example would help:

My config file appSettings.php is in app/config, just an example:

return array(
     'color' => '',
     'texture' => 'mixed',
     'layers' => 3
);

My DataSource class DataSource.php is in source/DataSource.php, just an example:

public class DataSource {
   public static function load() {
       if (Config::get('appSettings.color').empty()) {
           return false;
       }
       // Do other validations etc..
       return true;
   }

   public function getColorForRoom($roomId) {
       return something;
   }
}

Now, what is the right place for me to call the method DataSource::load()?. DataSource will be used in the application for fetching certain data like calling getColorForRoom($roomId) function.

Maybe in intializers or somewhere I could do:

if (!DataSource::load()) { 
    // Stop booting up Laravel
}

But I'm not sure where exactly to put this and how to stop the application from booting up.

Possible Solutions

I'm not sure if this can be the right way, but it seems like a good approach:

In my bootstrap/start.php:

require $app['path.base'] . '/app/source/DataSource.php';

if (!DataSource::load()) {
    Log::error("Failed to load datasource");
    throw new ApplicationBootException();
}

Again, I'm not entirely sure about this. Is this a bad solution or are there any other better solutions?

The other possible solutions are loading DataSource from routes or filters as mentioned in the below answers.

Upvotes: 2

Views: 1022

Answers (2)

Ross Edman
Ross Edman

Reputation: 823

Why don't you throw a custom Exception? Then you can catch this exception and redirect to a view that is like a 404 but custom to your application?

public class DataSource {
   public static function load() {
       if (Config::get('appSettings.color').empty()) {
           throw new ApplicationBootException();
       }
       // Do other validations etc..
       return true;
   }
}

You could place this in the routes file.

App::error(function(ApplicationBootException $exception, $code){
    //.. your code here to handle the exception
});

Please note I am just using ApplicationBootException as an example. You would have to create this class and have it extend Exception

Upvotes: 0

Laurence
Laurence

Reputation: 60058

Well - you could put it in the filters.php file

App::before(function($request)
{
    if (!DataSource::load()) { 
         App::abort(500, 'Config is not correctly set');
    }
});

Upvotes: 1

Related Questions