What is a scope in laravel and what is the cons and pros to use it? - laravel-5.8

When should we use scopes in laravel and what are the advantages?
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}

It automatically adds extra conditions for SQL query for model (which are needed and which would be applied across the entire model).
Saving you time and effort instead of including repetitive code here and there to add these extra conditions every time a model is fetched. It effectively saves you time, you can also make-do without it by adding it by hand where applicable. it is like syntactic sugar lets say.
A major advantage is that if at a later time you want to update the conditions (eg your requirements change) you can easily do it in one place instead of browsing through entire code to find the extra conditions and update them.
For example take a look at this article about scopes in Laravel
Let's say for example that you want your model to satisfy some conditions (for each model call, ie global scope). For example updated_at > some timestamp AND type = some type. Instead of adding these conditions every time you call your model methods you add a (global) scope which includes them by default for every call. Like it was said, it is simply a time-saver instead of having repetitive and error-prone code here and there.

Related

Laravel / Eloquent special relation type based on parsed string attribute

I have developed a system where various classes have attributes consisting of a custom formula. The formula can contain special tokens which refer to different types of object. For example an object of class FruitSalad may have the following attribute;
$contents = "[A12] + [B76]";
In somewhat abstract terms, this means "add apple 12 to banana 76". It can also get significantly more complex than that with as many as 15 or 20 references to other objects involved in one formula.
I have a trait which passes formulae such as this and each time it finds a reference to a model (i.e. "[A12]") it gets it from the database with A::find(12) and adds it to an array of component objects which can be used for other processes later on in the request.
So, in essence, it's a relationship. But instead of a pivot table to describe the relationship, there is a formula on the parent model which can include references to child models.
This is all working. Yay! But it's really inefficient because there are so many tiny queries to get single models as formulae are parsed. One request may quite easily result in hundreds of queries. Oops.
I see two potential options;
1. Get all my apples and bananas from the database at the start of the request and get them from an in-memory store instead of from the database when parsing a formula (is this the repository pattern??).
2. Create a custom relation type (something like hasManyFromFormula) which makes eager loading work so that the parsing becomes much simpler because the relevant apples and bananas would already be loaded into the parent model.
Is there a precedent for this? As for why I am doing it like this, it would a bit tough to explain in brief but suffice to say it is to support a highly configurable data retrieval system which supports as-yet unknown input data configurations.
Help!
Thanks,
Geoff
Am not completely sure if it is the best solution, but in the end I created a new directory class for basic components and then set it up in the app service provider as a singleton. The constructor for the directory class loaded all models of several relevant classes and made them available as collections throughout the app.

acceptable MVC parameter usage

would it be considered a valid implementation if I do not use the model for certain parameters? For example a webform posting values directly to the controller which then passes them to another class. Is it necessary to make sure that all the fields in the webform are also referenced/stored in the model?
I consider it a valid implementation, but suggest that you do this only if the parameters you want to exclude from the Model are absolutely NOT going to be used by the View (other than for confirmation of data entry in your webform), AND there is no need for the parameters to be referenced again once handled by the Controller.
Yes, it would work, strictly speaking.
However, you probably want to use the model. You don't want to create a new variable every time you run the view, which would happen if you use the controller.
I would consider it valid implementation if you decided not to use the model for certain parameters. I believe there are instances where certain fields may not relate directly to the model in question therefore giving valid reason to break those fields/parameters off from the model.

Generating Navigation for different user types, MVC, PHP

I have this idea of generating an array of user-links that will depend on user-roles.
The user can be a student or an admin.
What I have in mind is use a foreach loop to generate a list of links that is only available for certain users.
My problem is, I created a helper class called Navigation, but I am so certain that I MUST NOT hard-code the links in there, instead I want that helper class to just read an object sent from somewhere, and then will return the desired navigation array to a page.
Follow up questions, where do you think should i keep the links that will only be available for students, for admins. Should i just keep them in a text-file?
or if it is possible to create a controller that passes an array of links, for example
a method in nav_controller class -> studentLinks(){} that will send an array of links to the helper class, the the helper class will then send it to the view..
Sorry if I'm quite crazy at explaining. Do you have any related resources?
From your description it seems that you are building some education-related system. It would make sense to create implementation in such way, that you can later expand the project. Seems reasonable to expect addition of "lectors" as a role later.
Then again .. I am not sure how extensive your knowledge about MVC design pattern is.
That said, in this situation I would consider two ways to solve this:
View requests current user's status from model layer and, based on the response, requests additional data. Then view uses either admin or user templates and creates the response.
You can either hardcode the specific navigation items in the templates, from which you build the response, or the lit of available navigation items can be a part of the additional information that you requested from model layer.
The downside for this method is, that every time you need, when you need to add another group, you will have to rewrite some (if not all) view classes.
Wrap the structures from model layer in a containment object (the basis of implementation available in this post), which would let you restrict, what data is returned.
When using this approach, the views aways request all the available information from model layer, but some of it will return null, in which case the template would not be applied. To implement this, the list of available navigation items would have to be provided by model layer.
P.S. As you might have noticed from this description, view is not a template and model is not a class.
It really depends on what you're already using and the scale of your project. If you're using a db - stick it there. If you're using xml/json/yaml/whatever - store it in a file with corresponding format. If you have neither - hardcode it. What I mean - avoid using multiple technologies to store data. Also, if the links won't be updated frequently and the users won't be able to customize them I'd hardcode them. There's no point in creating something very complex for the sake of dynamics if the app will be mostly static.
Note that this question doesn't quite fit in stackoverflow. programmers.stackexchange.com would probably be a better fit

MVC - Codeigniter

Where should intermediate code be placed? (something that ins't just storing/retrieving data from DB nor processing requests/views)
For example,
Say I have Listings and I create CRUD functions in the model. These Listings may require more complex tasks such as pausing and resuming, which may require some time calculations, error setting, etc. Should these be placed in the model or should I wrap a simple model in a library and use that as a middleman for the model?
At the moment I'm thinking of using Drivers/Libraries and keeping models rather simple, except for some dynamic SELECT filters. I'm getting a bit confused though, since I'm guessing I'd probably have to recheck variables, dependencies, etc in the model after doing it in the library, yes?
I'd most likely either squish everything together in the model and check once or separate and check twice?
The general rule of thumb is:
1) Perform all business logic in the models.
2) Perform actions like a traffic cop would in controllers. (directing users to new views based on results of activities.)
3) Perform only presentational logic in views.
Anything else that you would like to do that would be considered, "intermediary", could reside in a Library or Helper.
It should be noted though that if you write a Library, don't forget to get an instance of the current CI object in your class so that you have it to use with your internal class methods.
class Your_lib {
$CI =& get_instance();
...
}
Hope that helps.

MVC and Pagination

As an MVC newb, I keep getting caught up in the details. One in particular is making me pause longer than I'd expect; pagination. Should pagination go in the model, or in the controller?
In case it matters, I'm using ZF, and would like to paginate the results of some SQL data.
Pagination separates records between pages, so it only gathers data from the model, but deals with presentation. Unless it's intrinsic of the model to split the output in multiple pages (which rarely occurs), my suggestion is to put pagination logic (IE dealing with page number) in the controller.
You might also want to consider taking advantage of a view helper, to minimize the code you put into your controller (fat controllers aren't a good thing).
The thing is though, that Zend_Paginator has a very convenient set of adapters. One of these is Zend_Paginator_Adapter_DbSelect which allows you to enclose a Zend_Db_Select query for efficiently paginating a sql query (e.g. limiting the results). So I can see why you are wondering where to construct these. Although you can indeed debate whether the model is the best place, I personally don't have a problem with creating a method in my model like:
public function fetchEntitiesAsPaginator();
... which would return a Zend_Paginator instance injected with a Zend_Paginator_Adapter_DbSelect.
BTW:
I personally don't consider a paginator just for presentation. I just consider it as a glorified LimitIterator. When you look at it from that perspective, things are starting to look a bit different already. And as a side note: the presentation concerns of Zend_Paginator are seperated by the Zend_View_Helper_PaginationControl view helper already anyway.
Logic to paginate goes in the controller. Any data you need, for example the current page number, should go in the model.
When in doubt, data goes in the model and everything that acts on the data goes in the controller.
The controller should handle the parameter for the page number, and then pass it to the model, which will then know which records to retrieve.
For example...
$userModel->getAll((int) $_GET['page']);
(I don't know Zend Framework, but the idea should be clear)

Resources