Laravel Eloquent - Trait vs Observer - laravel

Lets say I have some models with the field "slug". On model saving, I want to set the slug automatically.
My first guess to do this, was to create an observer and reacting on the "creating" event. But after a short google search, I found https://github.com/spatie/laravel-sluggable
Why do they prefer Traits over Observers? When to use Traits , when should I use Observers?

Observers are nothing new but classes in Laravel Framework
You may use observers to group all of your listeners into a single class. Observers classes have method names which reflect the Eloquent events you wish to listen for
But Trais are for reusing codes
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
You use the package's trait in model and it does all the slugging-mechanism

The package of Spatie you linked uses traits to implement the code to your model, they listen to the events [here] just like you would do in an observer.
So they do it to make it easy to implement these features, via the trait.

Related

Where do I put "extra" default fields for a Laravel model?

This question is about the "correct" design pattern, not about functional code. I want to adhere to best-practices and use the right feature in Laravel.
I have a model called Order which contains users' product orders.
Order has several columns, like which product, quantity, etc, and is stored in mysql, with a belongsTo() call to the User model.
When I place an order using the OrderController, I call an outside API that I set up using a Service class.
Here's the main part of the question:
I need to add certain fields that the API requires, but on my end are always the same, so it would make sense to me to pack these into an object of their own and just append that object to the end of my Order data before submission.
So where is the "Best" place to put this extra data? In my model? In a Service class? I'm leaning toward the service class, but that just doesn't feel right.
You have an action that gives a single or a collection of a model. So the best practice for adding some extra data to those results is using JsonResource and ResourceCollection. By using them you can easily add anything you want in the ToArray method.
Lumen doesn't have Illuminate\Http by default but you can add it to your project.
Official Http package of laravel
Eloquent: API Resources Documentation.

Laravel: Should I stick with camel case names for Eloquent relationship methods?

Laravel encourages us to use snake_case, e.g. first_name, for model attribute names. In particular, when snake case is used to access an attribute from outside the class, it will automatically look for an accessor named getFirstNameAttribute.
When it comes to model relationships however, it seems more natural to use camel case. For example, if a stadium has multiple access points, then the stadium class might have an accessPoints() method. I can call this method as a property ($stadium->accessPoints) to retrieve a list of access points, or I can call it as a method ($stadium->accessPoints()) to get an instance of the underlying query builder.
This is different to how I would normally approach naming conventions. I would normally name attributes using the same case (either snake_case, or camelCase), irrespective of how the attribute is realised.
I am now embarking on a large Laravel project. Should I stick with the two different syntaxes, or am I likely to regret it down the track?
There's no true convention, like in Assassin's Creed's saying,
"Nothing is true, everything is permitted"
Laravel follows the PSR-2 coding standard. Source: https://laravel.com/docs/5.5/contributions
Which redirects us to https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md
(from https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md which says: Code MUST follow all rules outlined in PSR-1.)
And there it says:
Whatever naming convention is used SHOULD be applied consistently within a reasonable scope. That scope may be vendor-level, package-level, class-level, or method-level.
And from that declaration, that's related to separation between environment level conventions, such as database design conventions and code conventions. Most database design conventions encourage snake case column names, and most code conventions use camel case method names, class names etc.
And when defining a model, to declare that, that the model property relates with a database column, the coding convention changes from camelCase to snake_case.
Well, it is a convention, so you should use the approach you are more comfortable with.
I personally use snake_case only on column attributes and camelCase on everything else (class names, relationships ecc).
Note that camelCase for class names and methods is basically necessary, because all laravel and external modules classes and methods use camelCase. If you use snake_case, it will be a mess with some methods implemented by you in snake_case and framework methods in camelCase.
For relationships, you will basically only use relationships defined by yourself, so i believe you can really pick the one you prefer.

Laravel add custom method for all eloquent models

I am looking for a way to add few custom methods which will be used in all models. I can imagine 3 ways of doing it :
Adding custom method to main Eloquent's Model.php class file(I want to avoid doing this as this is a core file)
Creating a custom model class with required custom methods, which will extend to eloquent's Model class and all the models in the project will extend to custom model class.
Adding a trait which will have my methods and include it inside all models
However, I want to do it more efficiently and best way possible. Is their any other way to do it?
PS I am using laravel 5.2 as its an old project.
Based on the comment discussion and adding my experience in Laravel I would suggest you to go either with #2 or #3 approach as #ceejayoz have specified in the comments
first one is definitely a bad approach as you need to modify the core which is not at all a good practice. Second and third are both good approaches.
But, before that you need to check your requirements if literally all models (including any future ones your app will ever have) need the extra functionality, however you can use traits for all models.
If I have the choice probably I will go for traits over custom models as traits are relatively simple then custom models

How to name the layer between Controller and Model codeigniter MVC

I wanna restrict model to calling to db only
while controller will call model, libraries or helpers.
I do not want to put logic in controller nor in the model to prepare data for views.
Now the logic for preparing all the arrays for views are done in controller. I am creating a library to separate this part as sometimes i feel it is overloading the controller
Hence, i want to create a library class and make controller build the view data before throwing it to the view. It is not exactly templating.
The thing is i do not know how to name it.. Any good suggestion ?
I am thinking view_builder, ui_builder, ui_components?
Cheers
Here's how I'd layer the app:
View
Controller
Service
Persistence
View is either desktop or browser or mobile-based.
Controller is tightly bound to view. It's responsible for validating and binding input to model objects, calling services to fulfill use cases, and routing the response to the next view.
Services fulfill use cases. They know about units of work, own transactions, and manage connections to resources like databases. They work with model objects, other services, and persistence objects. They're interface-based objects, but can be remoted or exposed as web services - RPC-XML, SOAP, REST or other.
Persistence is another interfaced-based object. The implementation can be relational or NoSQL; the important thing is that the interface expresses CRUD operations for model objects. If you use generics, it's possible to write one interface that works for all.
I wouldn't have model objects persist themselves. I'm aware of the "anemic domain model" pejorative, but I think more exciting behavior should center around the business purpose, not CRUD operations.
Good setup. I also sometimes use CI libraries to work out the kinks in a returned data array before passing it to a view. I also sometimes just use the model.
And good for you for thinking about names - I think all the ones you mention are fine; you could also think about naming your library something like data_structure or array_to_object - or something more specific to your own problem like friend_map or tag_cloud.
My advice: pick a name, and then don't be afraid to change it if something more descriptive comes along or the function of your library evolves into something else. Find+replace is your friend.

Best practices for implementing models in the MVC pattern

What are the best practices for implementing models in the MVC pattern. Specifically, if I have "Users" do I need to implement 2 classes. One to manage all the users and one to manage a single user. So something like "Users" and "User"?
I'm writing a Zend Framework app in php but this is more a general question.
The model should be driven by the needs of the problem. So if you need to handle multiple users, then a class representing a collection of Users might be appropriate, yes. However, if you don't need it, don't write it! You may find that a simple array of User objects is sufficient for your purposes.
That's going to be application and MVC implementation specific. You might well define a class collecting logically related classes, or you could define a static register on the user class. This is more of an OO question than MVC.
I'll second Giraffe by saying the use of included collections is almost always better than trying to write your own.
But I think your original question could be reworded a little differently... "Do I need a separate class to manage users other than the User class?
I use a static factory class to build all of my users and save them back to the database again. I'm of the opinion that your model classes need to be as dumbed down as possible and that you use heavy controller classes to do all of the work to the model classes.

Resources