PHP Autoload and Namespaces [Extended Guide] | [2020]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody welcome to better PHP today we're going to be looking at PHP autoloading we'll try to understand why we need to autoload and also take a look at namespaces and autoloading with namespaces and also composer autoloading do stick to the end of this video I'm confident we all will have a really good understanding of autoloading and namespaces now first let's understand why we need autoloading here I have a very simple project a very simple setup I have some classes under the actions directory and some classes under the animals directory and I have the index dot PHP and all I'm doing here is I'm creating an object climb of the class climb now I have the include one statement and we know that in PHP when I need to call on a function or a class which is not in the current file I need to include that or require it now let me load this page and we'll see what happens well I'm getting yes can climb now if we look at the climb class it's a very simple class it's got a protected variable it's got a construct where I'm assigning a value and I have a two string method where I'm printing a statement for those of you don't know what two string is it's a magic method and anytime you have an object and you're trying to print that object PHP is automatically gonna run this method now let's say I want to call another class let's say dollar run equals new run and let's say I'm gonna pass false as the argument and I'm gonna print the dollar run object dollar run again is a class very similar to the client class where I just have a simple protected variable I have a construct which defaults to false and depending on that value I say either it's running or no it can't run so let me try to load this page now well we're getting a error and we know why that is that's because I've not included that file here at the top so let me go ahead and include the run dot PHP and if I reload the page it is working but this time it says no cannot run now this is why we need Auto loading now in any PHP project we might have tens if not more classes that are being instantiated which means I would have to write that many include one statement and the same would have to happen in each and every file where I'm calling different classes now this would become difficult to maintain and also it's not it's not very convenient now to eliminate this issue we have PHP Auto loading so to do this PHP gives us a very simple method called SPL auto load register so let's take a look at this method so the SPL auto load register basically takes a user-defined function as the argument and it takes dollar class name as the function argument now what does this mean this means anytime we have a class that is being instantiated in PHP PHP will automatically copy this class name and pass it as an argument here now we can use that and use the include one statement inside of this method so let me do that so I will write include once I can take the class name and let's not forget the PHP extension and I will comment these two lines and now hopefully this should work let me reload this page I'm getting an error it says no such file or directory we know why this is happening now if you see here we have the class name and we're trying to include the class name without the path now for this to work all I need to do is just copy the the path and append it to the class name now before I do that here's something else we can test I do have the test dot PHP which in the root directory it does not have any any other directory path except it it shares the same path as the index dot PHP so ideally this class should automatically load so let me try that so I'm going to create a new object dollar test and it's gonna be of the class test I'll comment these two and let me reload the page now there we go it's it's working that means the author load register is working so let's make it work for these two objects as I said all I need to do is I need to append the path here and I'm gonna reload the page and yes we're getting the output that we desire so both the objects are loading and it's working fine now here's one problem this auto load register method works fine for all the classes in just one directory that is the app classes and actions now what if I want to load the classes which are under up classes in animals now there are multiple ways I can do this I can either have another auto load register method or I can use some logic and include classes from different directories so let's first try that so one of the things I can do is I can check if the file exists in a certain directory in this case it's gonna be in the actions directory and if the file exists I'm going to load it else if the file exists in a different path which in our case is the up classes and animals then let's include all the PHP files which have up classes and animals and let's just this by creating a new object let's say dog and make it a new dog class now the DA class takes the dog name as an argument and it we have a public method that prints it so let me do that I'm gonna send Milo and I'm gonna print dollar dog get dog me let me just make this a little cleaner and now let me reload the page there we go so now I have the objects from one directory and also an object from a completely different directory so this is how we can use the PHP autoloading to basically load any class from any directory now we can also add an else statement because in case we have some classes which are in the root directory we can load them as well so just load the class name without any path appended dot PHP and let me uncomment the test object and this should work as well then we reload the page and all the classes should load it is working as expected now ideally what we do is we would keep the entire auto load method and end the logic in a completely separate file we can keep it in a file called auto load PHP and you can have this file in any directory I will put it in the our class's directory so I'll create a new file I'm gonna call it auto load dot PHP and I'm gonna copy this entire method and put it in the auto load PHP I'm going to remove these commented lines and for this to work I have to just write one line that is to require the said auto load PHP file which is under app classes slash auto load dot PHP let me reload the page it should not change it is working just as expected now there are a couple of things to note here we can have multiple auto load register methods and we can also have the function outside of the method itself so let me do that I'm gonna cut this I'm going to create a function I'm going to call it auto load one and I can pass this function as the argument here let's reload the page and it should work it's still working so one of the issues Auto loading this way is that as the application grows there's going to be more and more directories and that means I'll have to add more logic and add those directories as well and if there's any change to the structure of the directory I'll have to make the same changes here also note that in PHP applications we tend to have a lot of third-party libraries so I'll have to consider those directories as well and anytime there is an update there I'll have to make the same changes here so when the PHP applications grow to a large size it's going to get difficult for us to maintain this to eliminate this issue we can use autoloading namespaces so using autoloading namespaces we can write just one single include one statement in the register file and all the classes in the PHP project will load automatically now before we get into how this is done we need to understand what namespaces are I'm not gonna get into the details of it but essentially what namespaces help us with is that when the application grows different developers might create the same class or the same file having the same name and this might cause a conflict and this will definitely cause an issue because PHP would not know which class to load here's an example I have a class dog under animals directory and a door class under the pets directory PHP will not know when I say instantiate the class dog PS we would not know which dog class to instantiate so to eliminate this issue namespaces were introduced so what means racence does is we can tell that this dog class belongs to a namespace which is humans and pets whereas this doe class belongs to a completely different namespace basically what it allows us to do is namespaces allow us to group different classes into different categories or different namespaces let's see how namespaces are written to write a namespace we have to write namespace and it is convention that we use the directory where the class exists so it's going to be up classes slash actions so what this means is this class climb belongs to a namespace which is add classes and actions now run is in the same directory so I can write the namespace up class is slash actions that means run belongs to the same namespace as the time now the dog is slightly different the dog is in a different directory so I'm good so I gotta write namespace up classes animals so dog belongs to a completely different directory now how does this help in the index dot PHP I can prefix that namespace so that PHP has no confusion so I will write our classless actions plank and the same would go for the run as well it's gonna be our class's actions and run the dog is going to be slightly different it's gonna be our classes animals and dog now I did mention using namespaces we can autoload using just one single include one statement let's see how that works let me remove all these lines here now if you see here when we add the namespace piece we will send the entire namespace and the class to the autoloading class name so what we can do is we can take the class name which will also include the namespace and convert that to kind of point to the directory now I told you as convention we write namespaces with the directory as the namespace so using this we can write include ones and you string replace and say let's replace the back slashes with the forward slash and take the class name so what this does is it's taking the class name which will also include the namespace and convert the namespace to the directory now let's not forget I need to also concatenate the extension and let's see if this works so if this is working all the classes should load and all the statements should run I'm gonna reload this page there you go so as I said using namespaces we can use just one single include one statement and we'll be able to load all the classes now another thing you need to note is it's not necessary that you have to use the directory path as the class name but it's just something that is convenient because that way we can have a standard or you can have any standard that set for your project and you can write a similar logic and just load all the files with using just one single include one statement now there's another thing that we need to note here now what if I have a namespace for the index dot PHP as well and let's say I call it index now if I try to reload the page do you think it's gonna work it will not that's because namespaces always take the relative part here it's trying to load the class climb as relative to the current namespace this is because sometimes I might have a directory under animals and that directory might have another subdirectory so instead of having to write the same namespace everywhere I can just keep relatively passing these namespaces and that's why if we look at the page here it's assuming that this namespace up classes actions is relative to the current namespace now to avoid that I can simply put a backslash here and it immediately realizes that this is an absolute path and I should not take it as relative to the current namespace let me do the same for the other classes as well and let me reload the file well it did work for the first three objects but I think it failed for the last one that is because I did not put the absolute path let me reload this page all the classes are loading a couple of things to note here is that the namespace should always be at the top of the file also the only other statement that can come before a namespace is a declaration statement also note that we can use a use statement which basically allows us to create aliases so I can just say use up classes and just give an alias like climb and here I can remove all of this and just write climb it should work the same it works the same so this is something that just makes it more convenient so that is it guys this is how we can use Auto loading namespaces to basically load all the classes in your PHP project using just one single statement now let's look at composure learning now for those of you don't know what composer is composer is a dependency manager which is our projects might be dependent on external packages and we wouldn't have to download these these packages or these code and then ship them every time we move the chord instead what we can do is we can declare these packages in compositor Jason and every time we build the application composer would automatically download these packages that they don't exist and also update them if we are looking for a new version if you don't have composer installed I will leave a link in the description just follow that and we can have composer installed now for those of you who have composer installed let's go ahead and setup composer in our project now to do that let me open terminal I will open a new window and I'm gonna navigate to the directory where we have the code documents docker PHP and I believe I have it in the code directory let me list all the files as you can see we have the app classes directory the index.php and the test dot PHP now for me to set up composer let me see if I have composer installed I've set up composer at a global level so if I I should be able to run composer anywhere from the system as you can see I have composer setup so to initialize or or set up composer for the project I need to use composer in it well it's asking me for a package name I'm gonna call it maybe autoload names spacer it's asking me for a description I'm not gonna give it any description it's asking me who the author is I'll skip it I'm not gonna I'm just gonna go with the defaults this is what I was talking about here we can we can tell composer what are the dependent libraries or packages that we need for now I'm gonna say no it's now asking me what are the development dependencies I'm gonna say no and it's just asking me well I have the composer Jason ready do you want me to generate it I'm gonna say yes now let me close dominum and here let's see if we have composer Jason there we go we have the composer Jason now this is the structure of the composer Jason file and I did say we'll have a required segment now anything we include here under the required segment will get automatically downloaded and set up in the project now let's take a look at that as well now let's say I want a and most of the packages are you'll find them at a site called packages org if you go here you can look for if you know what package you want to download you can basically look for it here I'll use a package called carbon this kind of helps you with with with modifying your your time stamps and basically working with with time so to use this either I can run the composer required statement in the terminal or I can just mention this dependent part that is the nest pod carbon in the require segment of the composite Jason and it should work so let me copy this here I don't have to mention the require statement I just need to say I need next pod carbon and also here I can mention what version I need I could use an older version or I can use the latest version here which is 2.3 3.0 when we are talking about the versions there are a lot of options here I can use the up arrow and it means it will download any latest version which is greater than 2.3.3 and I can also write something like this and this would download the latest version that is two point three point two point three three point whatever the latest version is so there's a lot of options here for now I'm just gonna fix it to two point three 3.0 and for that I'm gonna open the terminal and here I'm gonna run composer update and you'll see that it's looking through the dependencies and it's gonna download that dependency and what it will do is it will basically create a new directory called vendor and create the package inside that vendor directory so let's go ahead and you'll also see that every time we run composer update there is something that says generating author log files we'll talk about that when we get into composer autoloading so let me quickly move to the court and as I said we have a vendor directory here and if I open this you will see I have nest bot and carbon you notice there are other directories here as well that is because despot carbon also has certain dependent packages that it needs for it to run so if I open the composer Jason inside next part here you can see under require it says I need all of this for me to run so this is how composer works it basically helps us in ensuring we have all the dependent packages set up on our system or set up in our project here's another thing that we see we see that composer also has its own or to load PHP and for composer autoloading this is exactly what we are going to exploit now let's say we want to auto load using composer in that case we would not need this auto load PHP so let me delete this file and let me set up auto loading in composer now for me to do that I need to type in auto load this is a new segment an auto loading can be done in three ways one we have PSR 0 standard psr-4 we have class maps now the PS r0 is not recommended I think it's deprecated so we can look at the PSR method psr-4 method so let me type in psr-4 so in PS are for standard for me to load all the classes every single class under the up classes directory all I need to do is type something like this our classes and two backslashes and write up classes now with this one line composer will be able to auto load all the classes inside the our classes directory now why is that now PSR requires us to follow a very strict standard of namespaces that is PSR requires us to have in namespace exactly in the manner that we have the directory structure and that's why when I say take take all the namespaces starting with app classes under the directory app classes it will generate all the namespaces under this sub category that is it'll take up classes and then go to actions and it will generate the app classes actions namespace it will take up classes and it will go under animals and it will generate all the app classes and animals namespaces so let's put this to the test what I'm gonna do is I'm going to again because we have a auto load segment added let me run the composer update again you see it says generating auto load files it did not have to download anything new so the only the only thing it had to do was it had to read load or regenerate the auto load files and if I go back to the application and if I reload the page remember I have removed I have removed the auto load file that we had if I go ahead and reload this page this should still work well I'm getting an error and I know exactly why we're getting this error if I go back to the code you'll notice that in the index dot PHP we are loading the auto load file which no longer exists so all I need to do is now lord the vendor auto load PHP file let me reload this page and this time it should work it says class client not found in index dot PHP okay that is because we haven't it's not loading because we haven't included the namespaces here so it's gonna be up classes slash actions and climb this is going to be up classes slash actions and run the dogs gotta be up classes slash I don't have a suggestion I'm guessing I don't have the namespace here I have to make sure I have the namespace otherwise it would not work so it's going to be up classes slash animals and now it'll auto suggest I'm short it's got to be animals and dog and let me reload the page now of course the test is not working because we don't have a namespace for it yet so I'll just remove this and we go to page and there we go using composer Auto loading we now have all our classes are loaded we don't have our own auto load PHP we don't have to write any of our own include scripts all we need to do is follow a very strict structure of namespaces which is basically the the structure of the directory and all the classes will load automatically also in composer Jason I did say that we have three ways one is the PS are 0 PS are 4 and name and class maps now class maps is slightly different to psr-4 we're in it does not require us to follow a very strict structure instead all we need to do is we need to mention the directories like up classes slash animals and up classes slash actions and what it would do is it would scan through all the PHP files including the ini in these directories and it will copy all the namespaces and then it will put it in a file inside the vendor directory and cache that file and we can just remove all of this and I will update the composer and ideally all the all the classes should load again there we go it's working so this is how we can use class maps and psr-4 to auto load using composer now so now the difference between psr-4 and class map is that the class map caches all the namespaces and it's ideal for production setting because we're not going to have a lot of new classes created and all the classes or all the namespaces and classes would be scanned and it will be put in a cached file in fact we can take a look at that file if you go to vendor composer and look for auto load class Maps you can see all the all the namespaces are kind of copied and set up inside this file whereas the psr-4 is more beneficial when using in a development framework that way as we developed we can add new files and we really wouldn't have to make any changes once we run the composer update all the new namespaces would be scanned and it would work well that is it guys to summarize we took a look at what Auto loading is why we need it how Auto loading is done with SP lot load register method and also what namespaces are and how these two work together and we also have a look at Auto loading using composer if you liked the video and if the video helped you please hit the like button and subscribe to my channel for more better PHP videos thank you for watching
Info
Channel: TechnoTrax
Views: 6,083
Rating: undefined out of 5
Keywords: PHP Autoload and Namespaces [Extended Guide] | 2020, PHP Autoloading Classes, php tutorial, PHP Autoload, PHP Namespaces, Namespace Autoloading, PHP Autoloading tutorial, What is PhpAutoloading, How to Autoload classes in PHP, Namespace Tutorial, PHP Autoload and Namespaces, PHP Namespaces 2020, 2020, PHP Tutorial on Autoloading, How to autoload classes, PHP Autoload and Namespace Autoloading Tutorial, spl_autoload_register, Composer Autoloading in frameworks, PSR-4 Autoloading
Id: JIfNaqA4STg
Channel Id: undefined
Length: 29min 29sec (1769 seconds)
Published: Wed May 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.