 All right, welcome to New Orleans everybody and welcome to the 27th Drupal con Could you hear me right there at the back? Yeah, great So I came here like a couple of days back in New Orleans. It's a great city. I went to the French quarters Bourbon Street, and I'm sure most of you guys have went there, too So yeah, it's a great city a great Drupal con. So, yeah Welcome here a quick note before we start our session Drupal Association encourages all of you to participate in the court sprints which will happen on Friday the 13th and So there's something for everyone. So if you are a newbie if you are a newbie to court sprints you could join the first-time Sprinter workshop if you are a pro if you know how court sprint works, you could join the general sprints Or if you want a mentored course print, you could join the mentored course print workshop as well So court sprints are a great way to contribute back to Drupal. So I encourage all of you to Go there and make your mark. Thank you. All right So many of you might have seen the session description and Many of you might have questions. What is type Drupal? So the answer is there's nothing like type Drupal. I've made it up so What did what what so what this really means is? Now all of you know, there is PHP. There's a new PHP out there PHP 7 It's a it's a brand new PHP with lots of cool features And one of the cool feature is the scalar type printing feature the return type declarations feature and Some two or three features regarding typing. So what we are doing here is We'll see in this session how we could leverage those features those typing features and write better code in general and Better Drupal 8 code in general. So that's what type Drupal is if we leverage PHP 7 it's typing features to write Drupal 8 code So we'll understand. What are the features of typing features of PHP? We'll look at some examples. We'll then look at a module which is created in D8 or Drupal 8 Which uses PHP 7? Let me quickly introduce myself. My name is Aditya You can call me Adi I work as a solution architect in blistering solutions, which is headquartered here in California Blistering has been involved in Drupal development since 2007, especially the headless or decoupled Drupal development And if you have any further questions, I mean, we have been fortunate to support many Drupal cons and Drupal cams We were the diamond sponsors for the last Drupal con in Asia in Mumbai and If you have any more questions you could contact me on this email or you could contact me on this to the handle All right, let us quickly go through the agenda for today first We'll look at the Concept of typing what it's generally means and this goes beyond PHP. This is a programming concept It's a very basic concept, but we'll get to know what is typing as a concept Then we'll see how different programming languages including PHP structure the type systems Structure the type systems including typing as a concept then we'll see the Existing type-hinting feature in PHP, which is not something new in PHP 7. It's existing previously. Also, we'll look at the type-hinting feature in PHP We'll look at non-skiller type-hinting feature We'll look at a feature or a flaw Whatever you can call it will look at type juggling in PHP So this is all which is this these five points are all existing in PHP So this is not something new in PHP 7, but what is new in PHP 7 are these things scalar type-hinting in PHP return type declarations in PHP 7 type checking modes type exceptions which are a part of a broader concept called engine exceptions in PHP 7 and Finally, we'll see about we'll see how we could use PHP 7 to write duplicate code using the principles that we have learned So yeah, all right So typing as a concept What does typing or type-hinting means right? It simply means We give data types to variable declarations where we declare variables To parameters or arguments of a function when we declare a function or define a function, sorry Return value of a function and expressions. So typing simply means giving data types to variable declarations Parameters of functions or arguments of a function return value of a function expression This is a this is a pretty basic thing, right? This is not related to PHP. It's a basic programming cons concept so Now as we saw right Typing means giving data types to variables parameters return values Now various programming languages Structure their type systems according to these rules now like in PHP, right? In PHP, we don't give a type of a variable by defining a variable So these rules are different in different languages and languages structure their type systems according to these rules So let us look at those type systems and whenever you search about type systems You will get these four terms that we are going to see first is strong type system now what this strong type system means is These type systems generally don't allow type violations in your program now what type violation means is Suppose you declare a variable you declare a variable as an integer and Then somewhere down the line in your program. You assign a string value to your integer So that is a type violation, right? You declare an integer It's supposed to have an integer value, but then down the line you give it a string value So there's a type violation. So strong type systems Generally don't allow type violation. It will they will throw and compile error or they will throw and Runtime exception when you try to do that Some examples of languages having strong type systems are Java and Python Second is the weak type system We tap system is a system where in case of type violations it allows it basically performs some kind of type conversion So let's let's take the same example. You defined an integer You gave that integer an integer value, but it's at some point in your program. You assigned that integer a string So it will try to convert that string value into integer So it will try to convert some kind of try to do some kind of type conversion PHP is an example of weak type system static type system these the languages having static type systems are Java and C sharp They are more likely to throw and compile time error If there are type violations in your program So they check the type violations at compile time The last one is Dynamic type systems They interpret the value of an variable the type of that variable or type violations at runtime So, yeah, so these are the four type systems that we generally see when you talk about typing or type-hunting So, yeah Now these four types of type system Generate or give us an interesting two-dimensional space if you see here A language a programming language could could either have a strong type system or a weak type system a Programming language could have either a static type system or a dynamic type system So strong and weak are like opposites static and dynamic are like opposites. So Java here is Having strong type system and a static type system. What that means is Java is likely to throw compile time errors if there are type violations in your program and Yeah, and it's more likely to not allow type violations in your program and So Python right Python is an example of strong typing and dynamic typing PHP our own PHP is an example of dynamic and weak typing Okay, so any questions still here, okay, right? So what one important point here is nothing is absolute in this case So there's nothing such as absolute strong typing system So this diagram or this classification just shows you that Java or Java tends to be a strong type system tends to have a strong type system and Java tends to have a static type system So there are still some components in Java Where which follow the weak type system? right now we'll move on to type inting in PHP What type inting is it simply means It allows you to specify the type of data which a method is expecting. So let us look at this function. I Have one function are the function That accepts an integer array an array I Have called this function at the bottom By passing it an array So are the function what this code tells you is are the function? accepts one Argument which is array. So that is type inting simply you tell the function that you will accept You will expect an array as an argument It's type inting. Yeah, so we saw about type inting which is just specifying the type of Your argument then we'll see about non-scalar type inting Now before that, let me explain you the difference between scalar and non-scalar variables non-scalar types and scalar types Scalar types are your primitive data types like integer boolean string float and non-scalar types are your complex data types like objects arrays callables interface so So these are non-scalar and scalar types now what PHP 5 supports is they support non-scalar type inting Yeah, so the same example that we saw earlier. This is PHP 5 by the way The same example Function are the function has one argument. It takes an array it prints an array and We are passing it in array. So everything should work. Well, this snippet should return you should print an array correct now Let us look at this example This example would give us an error Yeah, it will give us this error. So let us look what this error is Argument one passed to are the function must be an instance of int Integer given so what this means is PHP 5 doesn't support scalar type inting So you could not suggest that dollar my integer could be an integer float boolean or string So what this does is? the the the system hunts for a class named integer and It expects Object of int class integer class In this function, but it doesn't find any so that's why it throws an error argument one passed to are the function Must be an instance of integer So that means page if I doesn't support scalar type hinting yet so So by not having scalar type hinting What is the issue? What's the problem right? So the problem is type juggling So type juggling is a feature Where we convert a variable type to the most appropriate variable type according to the action performed to explain it further Let us go to this function It's a very simple function. It just accepts two arguments It compares the first argument with the second it prints If the first argument is less than second argument it prints first is less than second otherwise it prints second is less than first So everything looks fine here. We have a function. We have two arguments. I've called the function with two integers Very simple, right? This should return you first is less than second Correct. All right, ten is less than 12 first is less than second so now look at this What I'm doing here is instead of passing 12 as a second input or second argument in the compare function I am passing a string foo. It still gives us and valid output Which is second is less than first now? This is something this is a problem. This is bizarre because ten and a string called foo cannot be compared But it will still return you a valid Output that second is less than first And believe me, this is a very small function but if you have a code base which is huge and If you have some functions like this so in place of an integer you pass and string It's very difficult to debug or find out where the problem is because your program would be running smoothly There would be no errors, but it's still wrong, right? You cannot compare ten and foo So this is where the problem is now to solve this problem. What I need to do in this code is I need to Basically check if the dot if dollar first or dollar second is a integer or not Right this makes sense So I check if both dollar first and dollar second are Integers then only I compare them and now what we'll get now I call the same function with ten and String foo so it will return me an output. Please pass integer inputs. That is correct, right? So this function should accept integer inputs. I'm passing a string It should return me something to tell me that please pass integer inputs So I have to write this tedious Functions like this tedious check logic everywhere is integer is array is empty is set To check in my functions that if the types of the variable past are correct or not So this could be avoided in PHP 7 No PHP 7 Is a huge improvement or PHP? I don't need to tell you that There are many cool features in PHP 7 one is scalar type hinting So scalar type hinting was introduced in PHP last year and It was an RFC You can look you can have a look at the RFC here. The proposal was passed And scalar type hinting was introduced in PHP 7 Right, so it was one of the most controversial proposals in PHP So there's a very heated debate out there on if we if we should introduce Scalar type hinting on in PHP or not, but I'm not going to go there We the point is we have a feature called scalar type hinting and we are going to use it in PHP 7, right? so What this means is Let's look at the last example This example right So it didn't allow me to specify my argument type as integer It will allow me to specify my argument type as array object or callable which are non scalar types But now in PHP 7 This will work fine right, so what I've done here is I Have made the same function are the function it expects one argument which is integer I've specified that there should be an integer and I am calling the function passing an integer one So this should work well, and it should return me an output well output one So this this happens in PHP you could write in place of integer them You could write float you could write boolean you could write string as well Yeah, so this is the contrast I was referring to right. This is PHP 5. This is PHP 7 so PHP 7 You can specify a methods argument as integer you could pass and And it would work and PHP 5 it would it would throw off an error Now let's see here This is PHP 7 I'm sorry So I've made the same function function are the function it accepts an integer I've specified them argument type as integer and I'm calling the function by passing a string So this will return me an error and got type error Argument one pass to adi function must be of type integer string given so if you Compare this with my last example the compare function. I needed to check if the past Integer was indeed an integer or not, but at this stage PHP 7 does it for does it for me So it checks if the past Variable which is hey in this case a string which is not matching to The parameter hint which is integer or parameter type which is an integer it will throw an error Yeah, so this is the same example that we saw earlier compare function takes two variables it checks if the first variable is less than second variable and Basically equals or prints these statements accordingly So as you can see here the last time when we had executed this function it worked and It gave us an output second is less than first by comparing 10 and integer 4 which is not Which should not be done, but here in PHP 7 This piece of code will throw us an error the error would be uncaught type error argument to past to compare function must be of type integer string given Right, so this is how a type ending works in PHP 7 you specify the type hints of Your arguments when defining a function and we are calling the function You make sure that you follow the type that you're given so you cannot pass a string in where it's expecting an integer All right, so what are the benefits of scalar type ending right so we have seen scalar type ending But what are the benefits why it was introduced in the first place? So the first benefit is less bugs, so I we just saw a piece of code which compared two integers and It allowed us to compare an integer and a string and it still gave us an valid output but So I so these kind of bugs are very difficult to find Especially your code bases if your code base is very huge. So in that case type hinting defining your functions and Your arguments with type hints Will reduce your bugs Code readability if you give type hints to your function parameters It improves your code readability Jebus by looking at your code. You would see what this function does what this piece of code does Concrete function definition as I told you right so if you define a function Which accepts three arguments and if you specify the type of these three arguments You won't even need to look at the function documentation to see what the function does Just look at the function definition. You would get to know what this function does All right, so the next part of this is Return type declarations in PHP 7 which is a part of this broad scalar type hinting feature So by the way any doubts still here? all right, so in PHP 7 We could specify the data type of a return value of a function So if you define a function if it suppose if it's supposed to return an integer You could specify that this function is supposed to return an integer. So If you look at this code here in PHP 7 you could do that Function are the function same function It takes the same integer argument but here If you see the colon thing there, so I've written a colon space integer. So what this means is this function Will always return an integer So the return value there so this function would always return an integer So these are the return type declarations then add line number seven I've basically passing the integer there and it's returning the same integer So this function this piece of code would work and it will give Us the output one Okay, let's look at the same piece of code Now what I'm doing is I've defined a function Return value of return type of that functions integer, but this function is returning and string my string is a string So that is not allowed. So if you define a function with its return value as integer You cannot return a string same way if you define a function with its return value as string You cannot return anything else So this will throw of an error return value of rd function must be of type integer string return Okay, no, it will not allow null it will so So if your function Returns null, there's a possibility that it would return null. So you should not use type return type hints Yeah, it's an type error exception. Yeah, so we'll get to that later. Yeah. Yeah. Yeah No, I don't think so. No Okay Yeah, I could return arrays and objects Right. So what are the features of return type declaration, right? It's a nice contract between the caller and called function So if I'm calling a function, I could reasonably I could be reasonably sure that this function would return what what it is promising So if I'm calling a function which has a return value as integer, it will always return me an integer I could be sure of so I don't I didn't I don't need to check the output written by the function in my program I don't need to do those nasty is integer is string or Z is empty checks at my end But this is a good stuff. So yeah, as I told you no error handling required in the caller function So if I'm calling something I can be absolutely sure that the function which is returning which has a return type as A type it will return the same type Function definitions are more readable. It's basically complete So just one look at the function you would get to know what type of arguments it's expecting and What type of return value it should give and yeah, so how many of you are Drupal developers here? Sorry wrong question to ask but Yeah, so how many of you remember this is said and not empties Right, right So I understand I mean even even in the Drupal core functions like user load node load They are so user load cat return and false value if the user doesn't exist in the system So you have to check it in your code So if you have if you basically call user load function You have to check if the user load returns false That means the user doesn't exist in the system if it's written an object user exists in the system So point is in Drupal 7 code and even in Drupal 8 code You need to have such checks everywhere in your code Just for your Just to be safe just to be sure that you are handling all cases correctly so By using type hinting By using type hinting you don't need to handle these cases. So you could be absolutely sure that what I'm getting here What are the what the function is returning is an integer nothing else? all right Now we saw some concepts of typing non-scalar typing scalar typing Return type declarations now see now we will see How those types are implemented in PHP 7 so PHP 7 has something called as type checking modes So there are two type checking modes One is weak mode. So what this weak mode Does is it's your default checking mode? So whatever code you write in PHP 7 by default follows this weak mode and what weak mode does is It will still try to perform the type juggling or type type conversion in case the types don't match Right, so let us look at this piece of code You can define weak mode in your file by writing a declare statement line number three Declare strict types is equal to zero that means The code which follows and this would be the first statement in the file So the code which follows this declare statement will follow the weak mode and we don't need to do that explicitly because this Is by default PHP 7 by default follows the weak mode So let us look at the example here I Am defining the same function are the function which accepts an integer input and returns an integer But when I try to call that function using one But it is an string one This will this will be passed this won't throw off any error because what it did was it converted the string one into numeric one and And the for the program works well. So this is how weak mode works. It will still try to Perform type juggling or type conversion conversion if your past value doesn't match the function Type hint or pair sorry argument type hint. Now. Let us look at this This will return a san error Now, let's see what what's happened here same function Same argument same return value. I have just instead of numeric one. I've passed a string called hay Which is obviously it's not an integer So the con or the conversion failed type juggling failed It gave us an error and caught type error argument one passed to are the function must be of type integer string given Yeah, correct Let's say different kind of type juggling. Yeah, so weak mode still has some Backdoors so in this case it will still try to perform type juggling String one could be converted into integer one and that's why this function this program would Succeed, but this code would fail because he could not be converted into an integer right now Let's look at the strict mode what it is So strict mode very simple at the first line of your file Write this statement declare strict types is equal to one. I have used the same function are the function It accepts one argument integer argument. It returns an integer Now I'm calling that function down and I'm passing one which is a string one in this case It will not allow at all Because this is PHP's strict mode it will not allow a string value Even if it's one it will not allow a string value when it's expecting an integer value so this is a crucial difference between PHP's weak mode and strict mode so in weak mode It allowed us to pass a string one when it's expecting an integer parameter, but in strict mode it didn't allow us Yeah, sorry It's it's it's based upon a file So if you when you when you write a PHP file and if you write a declare statement here So all functions called from that file will follow the Strict checking in this case Yeah, weak mode very far Sorry, no So the point was the point. Yeah, sorry It's in a file So it's file wise so when you write a file and when you it should those are declared statement should be the first statement in your file and The functions which are called in your files the call the function calls would follow the strict the type checking mode that you are defined I don't think so because yeah, I think this statement should be the first line in your program Mm-hmm, right. So I mean I haven't tried that but certainly an interesting piece to look at yeah Sure. Okay, so the reason for PHP to Follow the default weak mode is they didn't want to enforce the type system on everybody So they still wanted to preserve the ethos of being a very dynamic and flexible language But still wanted their developers to use strong typing just in case if they want to use them You could very well use strict typing in your own custom code some Important points to note here Return type declarations are optional The only type conversion allowed is integer to float so if Your function is expecting an argument of float You could still pass that function an argument of integer because the argue the The point here is if you convert an integer into float no data is lost But if you try to convert a float into integer data could be lost, right? so Even in even in strict typing the only type conversion allowed is integer to float and Now is still allowed as a default value for a function parameter So this snippet is still valid What I've done here is I've created one function dexseps and float I've passed it an integer It type it allowed us to do so and it allowed us to set a default null value also Sorry, no, I don't think so. You don't pass So if you don't want to pass anything So that's that I mean there's a point of default value, right? No, this is just an example Right, right. So that is correct So this is just an example of to show you that this could be done I would not personally do it because that would defeat the purpose of typing for me But still this is something you could do. All right, so So anybody remember this the white screen of that right So anybody who has worked with PHP applications or Drupal must know this, right? So there was an error in your PHP script your PHP script halts and It does not return HTML and what do what do you see is an white screen of that? So PHP 7 has an interesting Tool which are called as engine exceptions. So what they do is they throw Your most common errors as an exception. So you could handle them and end your script or end your program gracefully So and type exceptions are one of those exceptions to answer your question So, yeah, look at this piece of code. I have one function which is expecting an integer returning an integer and I've passed it and string one and this is the strict mode as you can see from the top So this will throw a sand this will throw in type error. So I've caught the type error here and It will basically Allow you to handle in whatever way you like to So this is how type errors are thrown in PHP if there are type violations. So Some of you might think this is Drupal con, right? so What about Drupal? So what we are talking about PHP till now So what about Drupal? So I Believe Drupal 8 and PHP 7 is a great combination. I've tried that personally and Drupal 8 as an has a hundred percent pass on PHP 7 so all automated tests on Drupal off Drupal 8 Passed on PHP 7 so you could technically use PHP 7 in your Drupal 8 development Drupal 7 I think there are still a couple of issues to be solved. So Drupal 7 is not 100% compatible with PHP 7 but Drupal 8 is right. So let's look at Typed date module and what my what I mean by type date module is We are using PHP 7 to build a date module with the typing features that we just saw So it's a very dumb module. What it does is it takes and string it removes your spaces Converts your characters into lowercase and It will throw a string like this. So basically to convert your string into a URL format. Maybe. Yeah the module So sorry, so let me go back So This is the module a pretty basic module It's a form Where I could just write my name or any string It will return the slugified version of the string pretty simple, right basic now. Let's look at the code right so For those who know Drupal 8 module development. We have a info yml file We have a form Okay, so it's a very simple form It's a it has a URL field and a Submit button So what I've done here is Drupal 8 Recommends you to follow a service-based architecture. So whatever you have to do Create a service out of it and then inject your service into The piece of code where you want that service. So I am I have created a service Called slugify service, which is nothing but a class And a function inside it Right So it actually performs the operation of converting a string into its slugified version. It's a pretty simple basic code and yeah So if you could see I have created this service. I've extended an interface From here. So this interface has my function prototype slugify function And as you can see here, I have given type hints for every Parameter Right, so you could not do this in PHP 5. So this is something you could do in PHP 7 and if you try to run this Piece of code in PHP 5 it will throw an error. So Same thing. I've implemented the same function in my class where I've implemented that interface Same arguments return value And then I've used this function. I've injected that function Here in this form Via constructor and I have used this slug service slugify function So so this function I could be absolutely sure that this would return me a string and this would accept and string all the time So So the point is when writing our own services, we could start using the typing features. You could start creating Function prototypes like this and This would be a great way to start using the typing features of PHP 7 in your drupal 8 code So Yeah Yeah, so That was all from me. Any questions Could you go to the mic please? So in the last example you gave here, if you would implement an exception in drupal How would uh, how would you do that typically? You want to know how to catch an exception? No, just if you would Wrap an exception around this example the last example you gave you want to see how to catch an exception here In this example, yeah, all right. What I could do here is basically using this form using this function Try catch You could do that No, I'm just giving example how to catch an exception. So this in this case specifically we should do a validated form Technically when when writing code. All right, let's try. Yeah, you would throw you would set a form error in this example, right? You would you would set a form error in this example form error or you would do this in a validate Oh, so okay, so Uh, what I'm doing here is I'm just showing you how to catch an exception in case Uh, this logify function here accepts and string. So I'm passing an integer. So it should it's likely to throw an error So I'm just showing you how to Catch an error and basically handle it in your own way. Maybe show and message to and maybe redirect the user somewhere So you could basically write anything in your catch function and Handle that error. Yeah I worked with pdp5 So this concept here with uh adding the type to the function that only worked if you're using like you can't write A user contributed modules and post them with these concepts because then You correct Correct, correct. That's a good point That's a good point because you cannot force anyone to use php7 and your Contributed module then if you write a contributed module using typing features So you are generally you are actually forcing the users to using php7 But technically Drupal 8 could run in php 5.6 also So the best way to do it is to write your own custom code In php7. So if you're contributing modules, don't use typing, but it's more likely that you will see typed code in future As people generally progress towards Drupal 7. Yeah correct Correct. Okay, great. There's a lot of like endemic polymorphism in Drupal core, right? So you'll have these Dock blocks that are like correct. I'll take a string or an array or an integer and I'll process it According to the input, right? And then the same thing right like user load is you know, get a either a user object or a false so Is there some Accommodation for that with typing or is this so new to php that kind of like the question earlier? We can't say we're going to return a string or false Right, but how do you How would you suggest you handle that kind of polymorphism? Ah I think the best way to start is To when you're writing your own code when you're writing your own service that could be used in some other modules To make your own service as typed So basically your service would be typed But you are not forcing anyone else to do that same thing So you would have to as of now you would have to Do the error handling that we used to do But at least you could make your own module type that others won't have to handle that as of now So is there if i'm writing a so I have a Service right and it's gonna look something up and either return me an object or false, right? You basically in php7 still Couldn't type the return value because you'd either return false or an object Yes, yes Yeah, okay. Yeah Will typing reduce the need for triple equals? Triple equals no, I don't think so strong typing would not I mean, sorry the strict mode would not right Anyone else anything? okay, then uh, thank you and uh You couldn't have a look at that code and uh Get repository if you want to And please give the feedback for this session on this url Yeah, thank you