Laravel model containing multiple classes

2019-01-26 21:01发布

问题:

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 { }

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();

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).

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?

回答1:

Yes, you can create a database_handler.php file and do:

<?php

    Class Category extends Eloquent { }
    Class Post extends Eloquent { }
    Class Client extends Eloquent { }

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) Add this file to your app/models folder.

2) Add an entry for it on your composer.json:

"autoload": {
    "files": [
        "app/database_handler.php"
    ]
},

And then you'll have to

composer dump-autoload -o

3) Create a different folder for it and also add it to composer json autoload section.

You choose, Laravel will let you free to do whatever you want.