Question

I want to automatically include all of my custom controllers and models(Eloquent) with my application so i can have access to them from any part of my application.

That's why in my Slim Frameworks index file I have these two foreach loops:

  // Include all controllers
  foreach(glob("controllers/*.php") as $controller)
  {
    include $controller;
  }

  // Include all models
  //foreach(glob("models/*.php") as $model)
  //{
  //  include $model;
  //}

However this creates a problem mainly the second for loop where I include all models and the error I get is: C:\..\models\model name.php Cannot re-declare.. How can I solve this ?

Was it helpful?

Solution

I'd recommend strongly using Composer (http://getcomposer.org) to manage your application's dependencies. Use the autoloader that Composer provides to autoload your classes and you won't have to manage them yourself, thereby avoiding the issue entirely.

In order to have access to those classes in your application, pass Laravel's container to your routes with the use keyword:

$app->get('/', function () use ($app, $container) {});

You're now able to access anything in the $app instance and anything from the $container in your route.

OTHER TIPS

Have you tried using require_once instead of include? Something like this:

// Include all controllers
foreach(glob("controllers/*.php") as $controller)
{
    require_once $controller;
}

// Include all models
foreach(glob("models/*.php") as $model)
{
    require_once $model;
}

Also check for it's class name, if you have a class controller name User and also a class model name User. If there's something like this, you have to rename it's class. You cannot register a class with same name. Make something unique and verbose, like UserController (a resource controller for user module) and UserModel (a model for user module).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top