是否可以使用Laravel将所有已定义模型的列表放入项目中的一个数组中,以便可以在循环中迭代它们(例如
foreach ($models as $model) {
echo $model;
}发布于 2015-08-06 07:47:04
如果您的所有模型都在单个目录中,则可以列出此目录中的文件,然后根据文件名生成类名。我担心这是唯一的选择,因为Laravel不需要在任何地方声明模型-创建类就足够了。此外,列出存在于给定名称空间中的类也不起作用,因为一些模型可能会被实现,只是没有加载。
尝试以下代码:
<?php
$dir = '/path/to/model/directory';
$files = scandir($dir);
$models = array();
$namespace = 'Your\Model\Namespace\\';
foreach($files as $file) {
//skip current and parent folder entries and non-php files
if ($file == '.' || $file == '..' || !preg_match('\.php', $file)) continue;
$models[] = $namespace . preg_replace('\.php$', '', $file);
}
print_r($models);发布于 2018-03-13 15:44:19
我知道这个答案太晚了,但如果有人试图为类似的问题找到解决方案,这可能是很好的。
为了标识我的项目中的类列表,我简单地定义了这个小函数,它在返回SplFileInfo对象数组的\File Facade的帮助下帮助在运行时获取类
/**
* @param $dir
*/
function getClassesList($dir)
{
$classes = \File::allFiles($dir);
foreach ($classes as $class) {
$class->classname = str_replace(
[app_path(), '/', '.php'],
['App', '\\', ''],
$class->getRealPath()
);
}
return $classes;
}上述函数在Laravel中的使用
$classes = getClassesList(app_path('Models'));
// assuming all your models are present in Models directory发布于 2020-09-22 22:42:41
下面是我在生产中使用的Laravel助手:
if (!function_exists('app_models')) {
function app_models($path = null, $base_model = null, bool $with_abstract = false)
{
// set up this filesystem disk in your config/filesystems file
// this is just pointing to the app/ directory using the local driver
$disk = Storage::disk('app');
return collect($disk->allFiles($path))
->map(function ($filename) use ($disk) {
return get_class_from_file($disk->path($filename));
})
->filter(function ($class) use ($base_model, $with_abstract) {
$ref = new ReflectionClass($class);
if ($ref->isAbstract() && !$with_abstract) return false;
return $ref->isSubclassOf(
$base_model ?? \Illuminate\Database\Eloquent\Model::class
);
});
}
}像这样使用它:
// all models in the app dir, recursively
$models = app_models();
// all models in the app/Models dir, recursively
$models = app_models('Models');
// same as above, except this will only show you the classes that are a subclass of the given model
$models = app_models('Models', App\Model::class);
// same again, but including abstract class models
$models = app_models('Models', App\Model::class, true);下面是将文件路径转换为类的帮助器:
注意:这里有很多不同的选项。这是可靠的,简单的,并且对我来说效果很好。
下面是另一个详细介绍其他选项的答案:Get class name from file
if (!function_exists('get_class_from_file')) {
function get_class_from_file($filepath)
{
// this assumes you're following PSR-4 standards, although you may
// still need to modify based on how you're structuring your app/namespaces
return (string)Str::of($filepath)
->replace(app_path(), '\App')
->replaceFirst('app', 'App')
->replaceLast('.php', '')
->replace('/', '\\');
}
}https://stackoverflow.com/questions/31837075
复制相似问题