简体   繁体   English

Slim Framework自动包含ORM模型

[英]Slim Framework autoinclude ORM Models

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. 我想自动将我的所有自定义控制器和模型(Eloquent)包含在我的应用程序中,这样我就可以从我的应用程序的任何部分访问它们。

That's why in my Slim Frameworks index file I have these two foreach loops: 这就是为什么在我的Slim Frameworks索引文件中我有这两个foreach循环:

  // 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 ? 但是这会产生一个问题,主要是第二个for循环,其中包含所有模型,我得到的错误是: C:\\..\\models\\model name.php Cannot re-declare..我该如何解决这个问题?

I'd recommend strongly using Composer ( http://getcomposer.org ) to manage your application's dependencies. 我建议强烈使用Composer( http://getcomposer.org )来管理应用程序的依赖项。 Use the autoloader that Composer provides to autoload your classes and you won't have to manage them yourself, thereby avoiding the issue entirely. 使用Composer提供的自动加载器自动加载您的类,您不必自己管理它们,从而完全避免这个问题。

In order to have access to those classes in your application, pass Laravel's container to your routes with the use keyword: 要在您的应用程序中访问这些类,请使用use关键字将Laravel的容器传递给您的路由:

$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. 您现在可以访问$ app实例中的任何内容以及路径中$ container的任何内容。

Have you tried using require_once instead of include ? 您是否尝试过使用require_once而不是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 . 此外,还要检查它的类名,如果你有一个类控制器名User ,也是一个类模型名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). 创建一些独特且冗长的东西,例如UserController (用户模块的资源控制器)和UserModel (用户模块的模型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM