PHP Enums tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
we're now going to have a look at enumerations or enums as they're more commonly referred to as and these were introduced in PHP 8.1 and what they do is they provide a way to define a fixed set of possible values what do I mean by that if we think of something like cardinal directions there is only north east south and west they are a fixed set of possible values and so that is what enums helps us achieve and so no random Rogue values get into there they will only ever be that fixed set and so I think the way we'll attack this is we'll first start out with a little example and show how that can be improved by using eoms instead of things like integers if you like this lesson then you'll love my object oriented PHP course which covers a lot of the stuff that you'll see in this video such as composition type hinting and serialization as well as all the essentials of objectoriented programming in PHP it's definitely going to help you so I'll leave a link in the description and at the end of the video so here I have a response class and these are the three Constructor parameters so we have string for Content we have an integer for status code and we have uh an array for headers so the content as long as it's a string that could be anything same for headers we could have lots and lots of headers however the interesting one here is status code because there are a fixed number of status codes there's about 60 different HTTP status codes and they are represented with an integer for example the integer 200 means okay 2011 means that a resource has been created and so you get the idea there but what we'd like to do is make it strict because at the moment we are just type hinting an integer here which means that we could pass integers which aren't actually one of those status codes so first off let's just uh go happy path and nor with this we'll pass a status code which is allowed and then we'll start to have a little think about well what can we actually do about when we get status codes which are not allowed okay so one possible solution is to use constants and you'll see this uh quite commonly in use for this kind of thing if you look at like uh response and request classes which are currently uh in circulation out there in the PHP world then you'll see that constants are used quite widely for this kind of thing so for example if we want a HTTP okay status code which will be 200 you can have a constant like this and then when we go to instantiate a response then we can just use that uh constant like so so there we've created a response and this HTTP okay will evaluate to 200 so we're doing the same thing as this except instead of just passing in some arbitrary number we we know that if we actually use the constants on the class then we are going to pass something which is valid however the problem does still exist because even though we are using constants there's still nothing which will stop someone from just saying uh whatever just making up some random number or for some way for a invalid number to be passed into the response by your system and so you could add validation to your response class which would probably involve adding all of these to an array and checking or having some kind of validation method which will check if the Response Code which has been passed is in the array the allowed list of uh response codes but now that we have enom we can do things a much cleaner way than that because they will already do your checking for you so let's go ahead and create one I'm just going to do it in the same file and we're going to move these files out here eventually but for the time being let's just work in here so the way that you create an enom is you use the keyword enum and then you need to give this a name so here we are dealing with HTTP status code so we shall call it HTTP status code and then I'll drop my curly braces onto a new line and the way that you add the values to these is you use the case keyword and so for example in the case where we have a HTTP okay we can just say case okay like so okay so what we creating at the moment is something called a pure enum so you'll notice that this doesn't have a value is holding the value 200 we're going to get to that in a second when we look at backed enums but first let's just go ahead and create a pure enom so this is how I finished it off I've just added in in some common HTTP scenarios here created bad request forbidden large headers internal server error so this is okay but for our case we'd really like to have that code in order to do that we need to create something called a backed enum which means you are backing each case with a value and so let's go in and actually add some values the way you can do this is you say equals and uh I'm putting 200 for okay and you'll notice I'm getting a squiggly Red Line an important thing about back enums or a couple of important things is you need to specify what type of values you are using and we're using integers you can only have a choice of two they need to be either an integer or a string there are no other types which are allowed so here we're going to say integer and then once you do that every single one has to be an integer you can't combine ins and strings so doing something like this int string or if I can spell it right in string you can't have Union types it needs to be one or the other very strict about this and that's the thing with e nums the whole point of them is so that you are supplying only valid values and so we're giving a stronger type and a meaning to parameters when we pass these things in okay so now each of our cases has a value we can actually go ahead and use this in our our response and so instead of passing an integer now what I'm going to do is I'm going to pass an e or I'm going to pass the HTTP status code okay so that is now the type which our response expects and so for example if we want to pass the okay status code the way that we would do that will be like this HTTP status code okay just going to delete this one now we don't need that anymore now that we've done this though you might be thinking well how do we actually get at that 200 value on our HTTP okay status code and the answer is there is actually a built-in property on enums or unbacked enums called value so let's have a go at retrieving that and we'll do it in a fairly realistic way so it's probably something you're going to want to retrieve inside of this response class so let's add a public function and we'll call it get we not say status code that might be misleading because you might think well we're going to return an enum from that we'll say get status code value just to be explicit and we know that this should be an integer and we do have type safety there and we can say that we know that this will be an integer because we have this type hinted here and these values can only be integers sorry if that was really obvious but sometimes you just never know okay so what we're going to do is return from this we'll say this status code and you'll notice PHP storm is giving me some Auto completion I've got a choice of two things here and one of those is value and so we're just going to select that and then let's go and test this out so here we shall just Echo response get status code value just going to put a new line on the end of there and let's go and actually run this so PHP enums and as you can see we get a value of 200 now sometimes you might want to have a little bit more information or you might want your enum to help you with a little bit more information for example if we look at these here large headers is that really explaining what the error is to a human that doesn't really mean a lot to me in its current state and so what you can do is you can add methods to enums very important though you can add methods but you cannot add properties so you get the built-in properties such as value and name which you've just seen but you can't add your own because enums they have to be stateless so let's go and add a method here and we'll just call it get message in fact I'm just going to call it message and this will return a string and we can use match here so say for example we want to get a message for okay by using match like this so we can say return match and then this and then we can have a message for each of these cases so here let's go with self okay and this is the match syntax uses the Double Arrow and for this we'll just say success and then for each of these you can just create a message in the same way and that is what I've done here and so let's go and try this out just take one last look at the syntax before we do this so I've just created a public function message we're expecting this to return a string cuz we're creating a message for each of these cases and we can define those we can say self or we could have used HTTP status code but we'll stick with self and then down at the bottom here just going to remove some of this now so we'll say status code because you can store them in variables just like anything else status code equals HTTP status code and we'll go with the one that we use for the example large headers and then we shall just say Echo status code message we put a new line on the end of there okay we'll go and run this PHP enums and there we get the message request header fields to large and you can create methods for whatever you see fit it's not just for stuff like this where you're using match whatever you think might help you use the information which the eum is containing but one thing I will say is that this is quite a common way to use this and you might see this used quite a lot all right now what I'm going to do is I'm going to show you some methods which we have available on enums before I do that though I think I'm just going to um initialize composer the way I'm going to do it though is I'm just going to pull in a package so symphony choir do d-d and we'll go with Symphony V dumper and this will just help me display things also I'll get composers autoloader cuz I'm going to show you also that a nums can be namespaced just like classes or anything else okay so at the top here let's just require require ones we'll go with vendor autoload and then I'll show you a method called cases so we'll store it in a variable cases equals and we'll say HTTP status code cases and then we'll just do DD cases and we'll go and run this again and so here you can see we get an array containing all of our cases you notice the curly brackets around each one basically that is telling us that each case here is an object and so an interesting thing to note is that not only is each case an object it's also a Singleton object in other words you can't have two of the same one floating around in your project let me demo that to help you make more sense of it we'll just say code one equals HTTP status code okay copy that a couple of times code two will be something else bad request but code three will be okay and so we'll just compare these so I'm just going to say DD and if you remember how we kept compared uh objects it was in one of the previous chapters just go and check that out so DD code 1 equals code 2 if we look at this we'll see that it's false because they are indeed different uh cases but if we compare one against three you'll see both of those are HTTP status okay which will evaluate to two objects but two of the same object okay and so that comes back as true so the next thing I'll show you is from and this is useful for example if you have a value 2 or one but you want to get the actual HTTP status code enum for that value the way that you do that is like this so we'll say code equals http status code and the method we are looking for is from and we know that all of these are going to be integers and so if we pass 2011 and then if we DD on that code as you can see we get HTTP status code created so again like I say important to remember you are getting an object for this in fact if we go and dump out the type so we'll say get type code run this again the type is object okay so what about if I provide a code which doesn't exist it isn't on our HTTP status code so if I say 1 2 3 4 let's see what happens this time and this time we get an uncal value Error 1 2 3 4 is not a valid backing value for enum HTTP status code so we get a fatal error for that if you look for 1 2 3 4 but that isn't a valid value on this enum okay there is one other and that is Tri from and what this does if it doesn't actually find that value is it will give you null instead of that so let's go and run this so instead of throwing that error out this time we get null and so if you're wondering which to use from or try from of course it all depends on your application the surrounding code but what I would probably do is default to using from and only use Tri from if I absolutely need it if I have an application which is going to also deal with null simply because it's just a little bit of extra protection you're only dealing with one type instead of null and one other type but like I say all depends on the application how the surrounding code has been written okay so we obviously don't want to keep this stuff all in one file and enom you treat them pretty much the same as classes and put them in their own files or that is the best practice so that's what we're going to do here but first off let's just go and create a new folder so we create a folder called Source SRC and then inside of there we'll create one called HTTP where we'll add all our HTTP related files and then we're going to create one called HTTP status code and I'm just going to take my enum cut it from there and drop it into here and I'm going to give this a nam space of app HTTP like so so make sure you get your casing the same as mine and then we'll create a response class you'll not notice the name space is already done for me so all I need to do is just go and grab this response class cut that from there drop it into there and then next what we want to do is make our auto loading work so over to composer Json and here just going to drop in a new entry so this will be autoload and then inside of there we want PSR for auto loading and I want to map my app Nam space to that Source folder that SRC folder the way that we do this is we say app and then you need your backs slashes in there two backs slashes and that will map to the source folder and then we need to tell composer to update its autoloading files and we can do this with composer dump autoload so composer dump autoload or alternatively bit shorter you can just do composer du it'll do the the same thing okay so let's just go back to the enums file and check that this is working just clear some of this out of here I'll say response equals new response I'll import that content we'll just make something up that's not important what is important is our status code so we'll go with HTTP status code okay going to import that as well and then headers will just have an empty array and then we'll test this out we'll just say response get status code value let's go and run this PHP enums okay and we get 200 let's change the code to something else I think we had 403 Forbidden let's go and run it again okay and so now we're getting 403 we know that our autoloading is working our name spaces are working and so enums they look like classes and they are fairly similar to classes and some of the things that they can do but there are specific rules and things which you can do with classes but you can't do with enums these need to be handled quite strictly in order for them to be effective and so like I say one of the things is you can't add properties but there are also a few other things for example you can't instantiate them using the new keyword there is no inheritance so you can't extend one enum from another and also most of the magic methods or the ones related to State at least won't actually work so there is a difference between enums and classes let's finish off with some serialization I think so uh in the previous chapter we did serializing and UNS serializing objects I just want to show you what a serialized enum looks like and so here what I'm going to do is I'm going to say say serialized response equals serialize response and then we'll just dump this out PHP enums okay so if you've not looked at serialized objects before then this is what they look like all of these things have meaning so the Big O here is 17 the o means that this is an object so can you spot where the enum is amongst all of this this is how enums are serialized so I've got a capitalized e here and then all the way up to there that is what a serialized enum looks like so maybe not as much information as you would have thought you might have thought that it would serialize the actual uh integer value for this forbidden HTTP status code but that doesn't happen it just actually serializes sort of the name of the case but let's unserialize it and see what happens so I'm just using the built-in un serialized function and I'm dumping out the unserialized response and the bit we're interested in is this and this is the status code as you can see which is a HTTP status code enum and you'll see that our value has come back so what it has done it's actually read the the type of status code seeing that it is a forbidden and it's just able to look at our HTTP status code enum and just grab the value from there and rebuild itself so hopefully now you've got a good idea of what enums are and how they can be useful to you remember the definition which we said at the beginning they provide a way to define a closed set of values for a type and that's exactly how we've used them to provide a closed set of values those close set values being HTTP status code we had a look at how you can grab the Val values for enums how you can serialize them how you can name space but also some of the limitations such as you can't add properties to them or add maging methods which uh interfere with State because we need to have strict values strict meaning for enums they are used to provide a strict set of values and you don't want that to be interfered with or changed or any values to come in which are outside of that closed circuit if if you like this lesson then you'll love my objectoriented PHP course which covers a lot of the stuff that you'll see in this video such as composition type hinting and serialization as well as all the essentials of objectoriented programming in PHP it's definitely going to help you so I'll leave a link in the description and at the end of the video
Info
Channel: Gary Clarke
Views: 3,379
Rating: undefined out of 5
Keywords: Gary Clarke, PHP 8, Enums in PHP, PHP Enums Tutorial, Object-Oriented PHP, OOP PHP, PHP Serialization, Serialize PHP Enums, HTTP Response Classes, HTTP Status Codes, PHP Web Development, Advanced PHP Concepts, PHP Courses, PHP 8 Features, Backend Development, PHP Enums Use Cases, HTTP in PHP, PHP Best Practices, Object Serialization in PHP, Web Application Development, PHP HTTP Handling
Id: 0BNXWbFa75w
Channel Id: undefined
Length: 22min 58sec (1378 seconds)
Published: Mon Oct 16 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.