Laravel模型包含多个类 [英] Laravel model containing multiple classes
问题描述
我是laravel的新手,来自Codeigntier.我试图掌握Laravel使用的模型/类/雄辩的约定.我知道我可以在数据库中创建一个名为类别"的表.然后,我可以在模型文件夹中创建一个名为category.php的文件,其中仅包含以下代码:
I'm new to laravel, coming from Codeigntier. I am trying to get to grips with the model/classes/eloquent convention that Laravel uses. I know that I can make a table in my database called, say, "categories". Then I can make a file in my models folder called category.php containing just the following code:
Class Category extends Eloquent { }
会自动使用名称的复数形式(类别")与表名连接,并允许我访问控制器中所有的Eloquent命令,例如Category::All();
which automatically connects with the table name with the plural version of the name ("categories") and gives me access to all the Eloquent commands in my controller like Category::All();
这是我不明白的:我是否需要为数据库中的每个表创建一个新模型?在那种情况下,我最终将在我的models文件夹中得到一堆文件,它们的名称类似于resource1.php,resource2.php等,每个文件都包含与上述相同的代码(替换类的名称).
Here's what I don't get: Do I need to make a new model for every table in my database? In that case I will end up with a bunch of files in my models folder with names like resource1.php, resource2.php, etc, each just containing the same code as above (replacing the name of the class).
我不能只创建一个名为"database_handler.php"的模型,然后将所有这些类放在同一位置吗?
Can't I just make one model called, say, "database_handler.php" and then just put all these classes into it in the same place?
推荐答案
是的,您可以创建一个database_handler.php
文件并执行以下操作:
Yes, you can create a database_handler.php
file and do:
<?php
Class Category extends Eloquent { }
Class Post extends Eloquent { }
Class Client extends Eloquent { }
您可以执行PHP所能做的任何事情,并且可以将许多类添加到单个.php
文件中.但这不是一个好习惯,Laravel只是使用最好的应用程序来开发应用程序.
You can do whatever PHP let's you do, and add many classes to a single .php
file is something you can do. But this is not a good practice and Laravel is all about developing application using the best ones.
要自动加载此文件,您可以执行以下其中一项操作:
To load this file automatically, you can do one of many things:
1)将此文件添加到您的app/models文件夹.
1) Add this file to your app/models folder.
2)在您的composer.json中为其添加一个条目:
2) Add an entry for it on your composer.json:
"autoload": {
"files": [
"app/database_handler.php"
]
},
然后您将不得不
composer dump-autoload -o
3)为此创建一个不同的文件夹,并将其添加到composer json自动加载部分.
3) Create a different folder for it and also add it to composer json autoload section.
您选择,Laravel将让您自由地做任何您想做的事.
You choose, Laravel will let you free to do whatever you want.
这篇关于Laravel模型包含多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!