This seems like it should be a fairly simply question, but with Laravels (5.1) model factories, am I supposed to place every model definition inside the one ModelFactory.php file?
If, for example, I have 200 different models, I can see this file (Database\Factories\ModelFactory.php) getting very large and cluttered.
My question is:
Is there a better way to organise model factories, or should I really define them all in that one file? What is best practice?
If you have a look at the source code you can see that it takes the path (/factories) and requires every single file. So you can definitely create as many files as you want in that directory and separate them by concern or model.
Related
I'm developing a laravel app and would like to know some best practices.
As an example, I'm thinking about creating multiple controllers instead of writing more than 10 methods in a single controller.
I would like to know what are or( if there are any ) advantages other than code readability.
My main concern is that how does it affect when there are more files to compile by the PHP compiler.
Since I'm using a framework is it going to compile all the files or only the file requested by web.php
Some insight would be great!
If the 10 methods you have in a controller are all related, then keep them in that controller. If you have a FruitController with methods related to performing actions on types of Fruit, but you also include some methods for performing actions on Vegetables, move the Vegetable methods to a new controller.
Consider encapsulation when composing your files.
In general, avoid making files for the sake of it. If it makes sense to create a new file as the logic you intend to place inside that file has no other existing home, then fine, otherwise add your logic to an existing file.
I'm not sure splitting related code into separate files increases readability, large files can be readable as long as the code is well formatted and consistent (amongst other things). Check out this book on clean code if you're interested.
What you will get though is a decrease in productivity and maintainability by having to flick through and maintain several files that are all related.
There is no advantage of using multiple controllers instead of one controller, as long as it is related to one single model. You may say it increases readability, but this is better to unify them in one single controller which is associated with your model and try to pick expressive names for the methods. The main idea is to create one single controller associated with each of your models. Feel free to add as much as methods possible into your models to talk to your database and make queries and call those methods in the associated controller. Then you can trigger those controllers through the web.php routes to handle your data and pass them to the view layer.
When you create separate controller for particular functionality this is more readable for old and new developer.
Also please check this link
From laravel:
Instead of defining all of your request handling logic as Closures in route files, you
may wish to organize this behavior using Controller classes. Controllers can group
related request handling logic into a single class. Controllers are stored in the
app/Http/Controllers directory.
I recommend that you divide your logic into different controllers. For example you can place all your user logic into one controller userController.php:
Create User
Edit User
Delete User
Then create another controller to manage the logic for another controller like sending emails etc. In this way your logic is more organized, easy to work with and you can find and update your methods easier.
As far as I know, currently Yii 2 doesn't have an out of the box method to resolve ambiguity of controller and module names. An example of module hierarchy to describe what exactly I mean:
app\modules\v1\controllers\UserController // resolves the /v1/users and /v1/users/{id} actions
app\modules\v1\modules\user\Module.php // nested module, resolves the /v1/user/... controllers and their actions, e.g. /v1/user/something/{id}
In this case, the UserController conflicts with the user Module. The main reason of the ambiguity is the singular-plural magic of Yii 2 framework. I didn't find an appropriate solution to resolve this ambiguity. Further my ideas how to resolve it.
Rename the module.
Rename the UserController to the UsersController.
Create an additional submodule, and place there the UserController. E.g. app\modules\v1\modules\root\controllers\UserController
I'm not sure that at least one of these options is a quite elegant one and a proper solution in view of the Yii 2 philosophy.
Coming back to the main question, what is a more appropriate approach to resolve this issue by the Yii 2 philosophy? Controller and Module is two different types of objects, which is differently pluralized or not, thus should be right way to separate them in the routing for the described case.
How I usually deal with this depends a bit on how I'm structuring things.
Let's say I have users, departments, orders and maybe some other stuff. All these concepts have their own module in which all interactions take place. If I want to create REST controllers for all these concepts I can choose to add a controller to every module or I can create a dedicated API module for the controllers.
When creating a dedicated module for this purpose I usually name it api, maybe with some nested versioning module(s) inside. So in this situation I would get the following structure app\modules\api\controllers\UserController which would result in the URL /api/user. No ambiguity there and pretty clear what this is meant for.
When adding such a controller to the module itself I choose a better name than just 'UserController'. When asking myself the question 'What does this controller accomplish?/What does it do?' I find that just UserController doesn't cut it; Especially when inside a User module, resulting in /user/user. This controller is probably going to exist alongside one or more different controllers in the User module, all meant for something different. So, usually, I end up naming it just ApiController, resulting in /user/api. Another controller could be the ProfileController. So when looking at the URLs it's pretty clear what /user/api and /user/profile do. Without the ambiguity.
I am not sure I can fully understand the question, but probably you're asking about classname aliases?
use My\Full\Classname as Another;
I'm currently using Symfony2 and and I'm trying to divide my code into different controller (like an Ajax Controller, a User Controller etc...) but I don't really know when I should use a create a new One.
For example my DefaultController is starting to be quite big (~800 lines) and I was wondering if having a too long controller could impact the website's performance? (Longer loading time...)
And, if it does, when should I split the controller into smaller ones ?
I would say that you should group your actions by which operate on the same data (entities) or operate within a well defined responsibility. E.g. UserController for users, PostController for blog posts, etc. This means that if you want to create an action which role is different than the rest of the actions, put it in a separate controller.
Symfony is caching almost everything so I don't think that huge controllers would cause an impact to the perfomance but if you have a thousands lines long controller, I'm not sure that it does only one thing.
The controller's size can be a warning sign too for the misplaced queries and business logic. You should separate QueryBuilder calls into Repository classes and other logic to services and event handlers. You can save more lines by using annotations instead of PHP code.
I think it's a good idea to start with a controller for each relevant model, with a CRUD structure.
Of course it depends on your needs, but if you have a model "Post", you probably will need a PostController with CRUD routes and methods, like : index (/posts), new, update, create, delete...
Depending what you need you can delete or add some method relative to a
Post from this base structure.
Try to detect what is realy relative to a specific model in your defaultController and create a controller for it.
Good luck.
What #riska and #Yoann said all holds true.
In addition, I prefer not to create separate controller if I'm sure that it hold only that one method. In that case, I just put it into DefaultController.
From my experience, controllers are the part of UI layer. If you care a lot about keeping your controllers small, let me give you the best scenario you can make what a controller must do:
1.Call the appropriate service
2.Return the response
That is 2 lines of code for each controller action, or you can even make it in one line.
Like person above said, controllers are usually separated by what type of entities / services they operate on. If you for example have an entity - lets say User, the following actions are most likely to be in there: createAction, editAction, removeAction, registerAction, activateAction, loginAction, logoutAction and so on...
It does not have any impact on performance if your controllers are thin or fat. The code will be executed in the similar flow, and all classes are being cached in the production environment.
I have 2 projects accessing the same DB. One is with CodeIgniter, the other is a home made mvc framework. I'd like to use the same Model layer.
Is it possible to access Codeigniter Models from another project?
I'm not exactly sure why you would want to be accessing the same DB from two different frameworks at the same time (sounds like a recipe for disaster), but in general, I would say, "no."
What you actually want is not the model itself, You actually want the active records class located in /system/database/DB_active_rec, as that's the most common usage.
That class extends CI_DB_driver
This class accepts the config parameter for the DB(connection information).
You then want to extract the drivers themselves being used for the specific database you're working, the drivers can found at /system/database/drivers.
CI->model simply loads the DB_active_rec, that's why you need to do $this->db->insert()
I've never did so myself, But I don't see any major dependencies in the files themselves. I might have missed something though
I'm developing a app in laravel-4 PHP MVC framework
I'm wanting to develop some kind of utility class, for general coding tasks i carry out.
Such as: image uploading, image re-sizing etc... general application tasks
is it best practice to put all this in the base controller class? im thinking not, or defining a separate
UTILL::UtilityFunction();
// or
APP:UtilityFunction();
I'm not sure of the best way to structure this and keep it within best practice?
You're talking about a helper class, right? You better create classes to do whatever you need them to do, but they need to have a meaning on your app, they need to be specific, there's no problem creating a small class to do some image stuff and another one really small to upload files, but one utility class that does both is not good. Take a look at those articles: http://guru-php.com/blog/2008/08/128003/ and http://blogs.msdn.com/b/nickmalik/archive/2005/09/06/461404.aspx.
Using the same logic: you should add methods to your BaseControllers that are pertinent to all your controllers.
To create your utility classes, you can create a new directory (like app/library), create your classes inside it and add this path to app/start/global.php, in ClassLoader::addDirectories() list, Laravel 4 will autoload them automatically for you. Or you can add them to composer.json, using the autoload/classmap section and then run coposer dump-autoload to autoload them.