Today’s my talk is called “In-depth idea of Laravel Core files” and this talk is about to give you a better understanding of what’s happening under the root of laravel.
Also, I want to talk to you why it is important for you to know them because we heard already that laravel is a tool that we want to use but it will sum up if you know how it is working internally and that’s what this talk would be.
I want to take you on a little journey and we are going to take a look at three aspects of laravel. So first we have
Of Course, this topic is big and I can’t go to detail about all of them but I give you an introduction.
Why Do I care about Laravel Core?
There some common excuses not to do so:
It’s a tool, we just want to use it, why do we know how a tool works? Because if it’s a tool which is really don’t need to know how it’s build up.
- It takes a lot of time dealing with something big and complex application
- It can be done overwhelming especially at the beginning because it’s so big and so many things are happening.
Still, I believe there are some good reasons why you should care.
1. It Speaks to you : I say laravel speaks to you if you got question about method, just go to code and check out how the method is done and see all the parameters and laravel speaks to you and tell you how it’s working, it will tell you about methods and tell you about public attributes to use. of course, we have documentation but it’s always better to go into the code and see how it’s done because it’s much easier to understand that.
2. Debugging: Then you get to know your framework better makes debugging much easier. I am pretty sure you have seen it. You have got an error message if you worked in laravel before, you got an error message which sometimes makes no sense to you. Also, you don’t get to know where is this error comes from. You make a mistake here and error gets throw somewhere else. You can’t connect these dots together. It’s because laravel is quite complex and some kind of magic things happening here and this why we get the messages. The more you know the framework, you can easily connect dots together and will help you in debugging.
3. Learn from the best: Laravel is not only built by Taylor Otwell, but there also are more than 2000 contributors so many smart people put their heads together built something like laravel by looking at the solution and added code into the core. This is also the reason for looking into the core.
4. Become a better dev: At the end, all these will make you a better laravel developer.
Let’s start our journey and start with laravel request life cycle:
What is Laravel Request Life Cycle?
It starts to peercast your application then need to boot the framework and handle the request and make a response and send it back to the browser.
This is happening all the time every request hitting your application. Every time you refresh a page in laravel.
So this all starts from index.php file of laravel. So funny thing is the first line of code in index.php is constant called “LARAVEL_START” and it just shows current timestamp. You can delete this line and the whole framework will still work because this constant is not being used in the entire framework.
So for me, it’s funny because it’s the first line but still, it’s very important for packages of laravel like Laravel TeleScope or laravel-debugbar because you can do performance test when you know framework start booting up. This is why have this here.
More interesting is gets done and we go to the next line.
Second line here is the composer’s autoload file and here it starts getting interesting because of this line, you can use laravel classes and classes from the packages that we have been using. This is how the composer helps us to include framework classes.
In Next line, Taylor Otwell put that “Turn on the lights” so here, turning on the lights of the framework. This is done by requiring bootstrap app.php file. Here, a bunch of the things happening in the background to boot up the framework.
We are going to create a new application instance so it will go here
We can get back to php file is application instance which also serves dependency injection container. So This is what we got here. Then in the back is also bind the kernel which is going to use later to handle our request, we are also going to register base providers for event system, router system, and lock system. so, these are three core components that need and we are also going to set some base paths so laravel knows where the end of file systems.
Now next line, You can read this says “Run the application”.
Now this framework is booted up and now finally we can run the application and we can make use of requests. That’s what happens here. First creating a kernel instance by resolving the class from the dependency container. Then we are running the handle method.
Handle method on the kernel instance has a parameter that you can provide by the request so now you get request object here to the kernel handle method. In background now, laravel is taking this request and finds the correct route and create a response object.
So, If you going to return a few, you get a response object with html. So, Here is the response which already has an all the information we need in order to send it to browser calling send() method.
Of course, we need to send something to the browser to display to the user. Then we already coming here to the last line.
We are going to run the terminate() method on the kernel instance. Here, going to run some tasks that need to be done after the request has been sent back to the browser. So you can use this in your application as well for every middleware you can use terminate() method. So, if you have a middleware, you can find this terminate() method, you can run your task yourself after the request has been sent back or response has been sent back to the browser.
This basically already had in laravel Request Life Cycle.
Of course, there is a lot of things happening here in the handle method, you can match it all of your application log checks will be here inside this. You can check every file in details if you want to understand it’s core parts.
I am going to give you two example here to explain what’s happening there.
One of them is about Router:
REQUEST & ROUTER
I am going to take a look at method call, send a request to the router and it does exactly what does method says.
First, we are binding new request that we have that we got from HTTP request, it binds to the service container. So the next time, you are going to load request information, what you can do, you can control over whenever you need it. You will get a fresh instance of the request so this is why it is important that bind it here.
Next thing, what we need to understand is, it is clear a resolved instance for the request facade. I am going to talk about facades later but here it’s good to know every time you use a facade, we are going to store underline class of the Cache inside facade, so next time we use facade, we don’t have to load it again.
But now, it needs to clear because now it’s a fresh request and then next time you are going to use request facade, you will get fresh request, not an older one. This is why we Facade::clearResolvedInstance(‘request’); called here.
In the kernel, we also have some kind of bootstrapping underneath to be done in order to log more laravel functionality.
In the above image, loading the environment files (*.env) for environment variables that you to find but also loading configuration files which have some important information needed. Also, going to load all the facades so that you can use them everywhere in the application.
The last thing in this, is very interesting for me because it is using so-called pipeline param and I am not sure, have you heard about the pipeline param? So what Pipeline param does is pretty basic, you have an object and so-called pipes, you run the object through the pipes. Every pipe has a possibility to change the object in some way. The best example for this is done here in a file.
This is going to pipe all request through the global middlewares. This means sending a request object, global middleware run on this object. For Example, Global middleware is for trimming about some empty spaces. So that’s also been done here.
An idea of all request has been all these pipes, it is going to run the then() method, that’s on the last line here. Next, it sends the request further to the router.
The second example is, here in Router Class (is a different one from the kernel.php we see before). Two important things are happening here. First is going to need to find a route so findRoute() method called. It can do with the information passed in the $request because it stores the endpoint and stores the HTTP get/post requests. It takes $request to find the correct route and return matched one.
After that, the second step which is needed to run this route. Here, it has a thing between route connected to your controller. You can use a key to bind route to a controller. You can also use a callable anonymouse function connect to a route. In both cases, It is going to run the code within the controller or callable. In the back, laravel takes information, could return an object from a controller, laravel take a request object and translate it to a response object.
Alright, this is all about Laravel Request Life Cycle, Now, let’s go to facades.
What is Facade?
There is a kind of few things that I am going to talk about. People say it’s kind of magic or proxies or helpers. But the right thing is something different.
We are going to take a look, how facades works which will clear thing about facades:
In Example, going to find route for endpoint within that using Request facades to get the parameter year. The last line is the eloquent example which I will explain later. So now, taking request from facades.
What is happening here, is calling static get method on the request facade. Next, let’s check Request Facade.
What is REQUEST Facade?
Request facades, like almost all facades, are pretty much empty. There is only one method called getFacadeAccessor() and it returns some kind of string. There are no steps to get() method. So where does this come from?
So, you can see this class is extending base Facade class. So, let’s take a look at this:
What is BASE Facade?
If you look at this class, you will also don’t find any static get method here. But you will find the php magic method called __callStatic. What does it do? Every time you try to make a static method call, and the method doesn’t exist, it will find this method and called.
So, let’s check what’s happening here:
Here, you can get an idea of how facades work. Now, we are checking so-called facades root calling static::getFacadeRoot() method to get this instance here on this first line of the above image. Facades works like that, we have facades classes but they are all connected to a core class.
The request facade is connected to a class bind it to the controller through the request key. Here above, a $instance is an object of php which illuminates HTTP class. Next, line it checks if this instance exists. If not, it will throw an exception.
Next, it will execute the method(get/post) directly on the new instance. So, let’s check get method:
You can actually see the method we are calling so finally we found the method :P. This is how facades are work.
If you are using these classes means it’s just calling static method but at the end, it is not a static method.
Facades are misleading because not so obvious how it works, you have to take a little bit into it. After that, you get to know which class is actually being used.
Facade provides several helper methods which you can easily swap out the implementation so you can use mock inside facade. This makes them quite good to test.
Facades are tightly coupled to frame because you can only use it inside laravel.
In the end, if you want to you facades or not, is thoroughly up to you. Now, you know how it works to make your own opinion on it. I personally liked to use Facade. You have to define for yourself what you want to do.
What is Eloquent?
Eloquent is an Object Relational Mapper, means wants to make an object from data from the database someway. But it also uses the Active Record Pattern which means we are tightly coupled to how all database tables look like. Every table will have a model and every field from the table can be accessed within this model. We can save/update/delete directly on the model itself. It is very tightly coupled which makes on another side very easy to use.
As mentioned, models for every database table and there is some kind of builder to create queries.
I am going to take three database tables:
Here, Two primary tables are speakers and conferences. A related table is conference_speaker. It clearly shows, many to many relationships between speakers and conferences.
Now, get back to the example we have seen before.
Here, making use of request facade to get the year. Let’s say, to get all the speakers information of the year 2019. So you can pass a year in where a method of conference model to only get a specific conference of the year.
Next, trying to get the first one of it so you can use first() method and then want to get related speakers. So there are already a bunch of things happening here.
To make it little easier for a beginner. Let’s just try to get a conference.
So, how would be going about that again? What you can see, calling where the method of the conference model. Let’s check the conference model first:
You can see here, there is no where() method here similar to facades. But you can see here, it is extending a base Model class. Let’s check the Model class.
STATIC WHERE METHOD DOES NOT EXIST
And again, it is making use of static method as don’t have this method defined. It is creating a new instance of conference model and try to run the method on the model again but this time is not static method. So in our case, it is calling where() method. Again, it doesn’t have where method in our model as you have seen before.
STILL NO WHERE METHOD
So, Now another php magic method is being called named as __call. It is the same as static method but this time is not for static method. So, let’s understand what’s happening in there
First, it is checking is about increment or decrement which is not our case. So, It will make the use of the next method forwardCallTo(). We are going to move this method call forwardCallTo() to another object.What we get here is when we use this newQuery() method is to get a new eloquent builder. Now going to run the where() method on the eloquent builder. This is also where we finally got our where() method. It’s inside the eloquent builder.
It’s kind of quite interesting here to forward this method to the eloquent builder. I am not going in detail about how where() method is working. Here, it’s making a constraint for the query that we get specific results back but in the end, it returning instance itself. We can change the method in this again.
Eloquent/Builder trait BuildsQueries
If you remember correctly, after where() method, there was the first method(), to get just one result from that. Inside the eloquent builder, we can also make use of first() method which is defined inside of trait called BuildsQueries. We can make use of it inside the model.
First method just translated to another bunch of methods. First, we are taking just one element to take one conference. Then running the get method. The get() method executes the query that we build before. So now we actually get data back and will get back as in form of laravel object. This is why we need to use another first method here which is not method in the collection class to get just one object back.
So, This is how we can get a conference but now what about speakers. Let’s understand how we get the speakers?
GET SPEAKERS FROM CONFERENCE
It looks like calling the property of the conference class because first() method returns here a conference instance.
As we have seen before, conference class doesn’t have speakers property. See in below image
So where does it come from? We only have this method define relationships so let’s take a look at the base model class.
Base Eloquent Model
In this, we have another magic method. Laravel is using almost all magic methods of PHP. This time we are trying to access property on an instance.
Now, Laravel tries to get this property from the getAttribute() method to get the attribute. Every time you get a field like id, name, username or object from the database, this method is being around. But our case is different, we are not trying to get a field from the database table but trying to get related models
So How does this works?
First It is checking if the key and decide the attributes is the key of the database table and is not our case. Then try to see class itself contains a key which is also not our case. So then laravel thinks, okay if it’s not the first case and not the second case so maybe something else to do with relationships.
And that’s the last line being called to get the related data and this is how we finally get back our speakers.
I gave you lot of information about eloquent and I am sure it is a little bit overwhelming but I hope I explained it very well that how laravel makes uses of magic methods in order to provide easy to use interface.
In the end, More you know about the tools, better you will become as developer and laravel is one the tool so please don’t forget that.