Advanced search form with PHP | Sebastian Sulinski | Skillshare

Advanced search form with PHP

Sebastian Sulinski

Advanced search form with PHP

Sebastian Sulinski

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
52 Lessons (13h 24m)
    • 1. Introduction

      1:34
    • 2. Exercise files and dependencies

      12:58
    • 3. Environment and PHPUnit

      10:32
    • 4. Database manager test

      9:08
    • 5. Database drivers

      21:22
    • 6. Database execute method

      11:11
    • 7. Inserting new record

      15:12
    • 8. Database insert method

      15:09
    • 9. Database update and fetchObject method

      20:16
    • 10. Fetch object tests

      8:12
    • 11. Remove and count methods

      13:08
    • 12. Fetch objects and bootstrap

      19:40
    • 13. Container

      15:31
    • 14. Abstract model class

      11:58
    • 15. Update, delete and all methods

      8:25
    • 16. Order By and Limit methods

      8:59
    • 17. Lookup model test case

      17:10
    • 18. Update and remove tests

      20:08
    • 19. Model refactoring

      18:06
    • 20. Form dropdown

      11:20
    • 21. Year class

      10:33
    • 22. Book class

      19:39
    • 23. Testing update, remove, all and books methods

      12:36
    • 24. List of books

      25:16
    • 25. Group concatenation

      15:22
    • 26. Search class

      33:05
    • 27. Sticky (Part 1)

      25:55
    • 28. Sticky (Part 2)

      24:19
    • 29. Concatenators

      20:00
    • 30. Abstract Query

      16:35
    • 31. Pivot classes

      17:22
    • 32. Pivot under test

      17:10
    • 33. Query classes

      11:10
    • 34. Filter class

      18:23
    • 35. Equals tests

      16:40
    • 36. Filter equals tests

      19:59
    • 37. Exists tests

      17:03
    • 38. Filter exists tests

      19:47
    • 39. LikePercentBoth tests

      10:06
    • 40. Filter like percent both tests

      11:10
    • 41. Filter set

      15:36
    • 42. Model search method

      14:54
    • 43. Filter manager

      16:17
    • 44. Search tests

      13:41
    • 45. Pagination class

      15:17
    • 46. Accessor methods

      8:14
    • 47. Pagination under test

      21:35
    • 48. Pagination view

      22:12
    • 49. Pagination view tests

      18:33
    • 50. Pagination test refactoring

      11:54
    • 51. Paginator

      5:27
    • 52. Paginator and view

      7:47
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

102

Students

--

Projects

About This Class

Learn how to code a component that filters uploaded csv file and removes any records with invalid or duplicate email address before importing it to the database using Laravel.

Meet Your Teacher

Hello, I'm Sebastian.

See full profile

Class Ratings

Expectations Met?
  • Exceeded!
    0%
  • Yes
    0%
  • Somewhat
    0%
  • Not really
    0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Your creative journey starts here.

  • Unlimited access to every class
  • Supportive online creative community
  • Learn offline with Skillshare’s app

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

phone

Transcripts

1. Introduction: Hi and welcome to this course on how to build an advanced search form with PHP, you're in this course. We will learn how to build the form that allows us to feel the results by using a text field number off, drop down menus as well as radio batons and check boxes to make a multiple selection. We will ride the database rapper for PHP PDO to fetch data from either in my SQL Mario to be all sq light database to ensure our coded as what it's supposed to, we will ride tests using PHP unit. If you're not for me, our testing just follow along and I'll be explaining everything step by step to split long lists of records into number of pages. We will ride the pagination component with previous and next buttons, as well as drop down menu toe easily navigate to the relevant page on any type of device. To complete this course, we will make use off the following tools composer to manage our colds dependency local server environments such as homestead, which is what I won't be using or any lamp stack such a swamp Zampa Mom, depending on your operating system, If you're missing any of these tools, please refer to our course titled Setting Up Local Environment, which is when I explain how to get it all installed on your local machine. There's lots to go through, so let's move to next video where we start by installing the exercise files. 2. Exercise files and dependencies: in Israel, we are going to set up our project. First of all, we need to Donald the exercise files to download the exercise files. Go to get hub that come for it slash ss the hyphen tutorials and the the repository that that we are interested in is this advanced hyphen surge hive Inform hyphen PHP. You can look for this dis repository. If you can't see it as the first item on the least simply type advance and it's going to come up with two different repositories, this one without the PHP audiences. For the older course, this is the latest one. So if we click on this hyphen PHP and all we need to do now is click on this download zip. If you are using Geats, uh, get happen the other account you can simply forget and then clone it to your local machine and obviously work with defiance this way. But just to simplify things for the time being, I'm just going to download it. If we now open it. As you can see, it's L bean decompress. All I want to do now is remove. Actually, if we go back what I want to do is to rename this directory rather than having dismasted here. We don't need this. Just the name off the repository. I'm going to use terminal to move these fires If I just navigate to home directory downloads l asked to see what we've got is exactly same as what we just saw in the finder window. This is the director wants to move to our cold direction. So m v, Advanced Beach be. And then we go Teoh squiggly line for its lush code, which is when I keep all my coat again. If you're not familiar with oldest police, check our setting up local environment course which all this is explained otherwise moved is director to wherever you want to have it and where you're going to set up your virtual house later on from some of in this director to the coat. Ah, directory. If I do, l s We cannot remove the zip far sorghum off. Ah, advanced. And there we go. Ls there no Farsi? And so now I'm going to navigates to my cold directory. And as you can see, I have two different directors here on this one is when I kept When I keep basically completed project which I showed you during the introduction video. And this is the one we're going to be working from, which is what we just moved to this dark. So we are going to navigate to it for so city advanced search for BHP l as to see what we've got inside l s a l to see everything, including them. The hidden fast which start with a full stuff like get ignored, for instance. So if you are planning to push your project to the repository, obviously, however, think pretty much set now, the first thing we going to do if we know, navigates to our at it's going to be using PHP storm for this purpose here. I'm going to click on open because I want to open this project so cold, which is under my home directory. And the one I'm interested in is this advanced search from PHP. Click on OK on the project opens and the first thing I'm going to do Let's quickly have a look at them fires the actually come with them with the exercise fast. The first directory you'll seize the Arba Diallo churches where all our cold will be placed and it comes with the migration and then another subdirectory and so on. It's basically it contains the cold that will be later on. Used to generate our tables that the migration. Basically, we've got two sets off SQL statements. As you can see, each of these files represent the create table statement fall in this case, my SQL and the same ones going to be used for murder to be if you're using Maria to be rather in my school and an sq light which different slightly same thing, each single table that we have fire for. For that with SQL query. And if you will open immigration, you can see it uses the database component which we have in Britain yet. So we won't be running this until we have this component written and it basically is. It contains and basically methods which allow us to create the stables by calling specific methods. And so Okay, so that's up, Director, than we have assets which contains CSS and JavaScript fans inside of the JavaScript fans, you've got S R C with up togs farm. This is their file that we have created if you need to add any extra javascript. You can use this file, create another one includes separately. Entirely up to you. The only thing that we needed actually for this specific course is this SST select Jake. We're plugging, which I've written, Elia, any allows us to basically, when you select something from the drop down menu in our case is going to be a bicycle. You want l to the page, It's takes you to the dispatch and that's all we basically using during this course and then in the least directors we have the cold bicycle, which is unified. So we were using deserve foundation June discourse. Feel free to use bootstrap on the out of styling. Ah, again, source here, within this source, we will see bicycle fall That's has been generated with gold file before Munif IQ ation Because we create the far first at this op c'est seizes under this source directory and then we, um, unifying everything to this dissed director. So these are our J J javascript and CSS Farms. We also have sounds farce. If you would like to modify anything, this is biting. Well, the cult for all these components is created So if you if you familiar with sauce obviously feel free to play with this. And then once we install away NPM dependencies, you can run the gulp. We have this gulf already as well here. As you can see, it includes our assets s CSS up Tazi Assess, which is the entry point for our sauce components here. And then it basically outputs this into this CSS source directory. And then we are men if eyeing it, as you can see here, we're taking this CSS file which was created earlier from Suss, and we magnify it is in this assess CSS um in here. In that case, it basically is. Gulp, hyphen, see, assess component. And we exported to this distributable director. Okay for Jeffers Could be only includes J query display gin and this up the GS, which does exactly same as we did with CSS. Basically composite and unifies the fire. Okay, so that's go fall. Then we have index of PHP, which only contains HD geisha male structure for our form and at least off records later on . As you can see, it automatically has JavaScript fall included here at the bottom and our autopsy assesses well, right at the top as well as I'm using here for awesome because I've used nothing about two icons. Feel free to remove it if you don't want these icons. Eso that's indexed ph. B. Then we have Pocket Jason, which contains older dependencies that I'm using Jr scores for for my assets as you can see foundation sites and then oldest gulp dependencies as well, as well as this SST select Jake. We're blogging and then we have BHP unit dot XML, which is basically configuration file for BHP unit. Everything set up again. You don't have to worry much about us. We will discuss a few points here later on when we start writing tests. But for now we can just close it. And then we have set up the PHP find, which will run once we have our database component written, which will basically make it easy to migrate, told the tables in one Go. Okay, so that's defense that we have, which come with the exercise fast. Let's now quickly create the composite of Jason File. It's a new file composer Jason and let's start with a set of Kelly brackets and the out also in between a double close. Remember, we are inside of the Jason far, so you have to use double quotes and no single quotes allowed. Here we start without our load, and then another set of Kelly brackets on and we going to go for PS are hyphen four then Colon and the United States of curly brackets and our names space. You can choose whatever you want to use. I'm going to simply use up with Capital A and then two bucks lashes, Colon and witch director. We want this name space 2.2. It's going to point to our up directors up for its Nash. That's our outer loader. And now done. If we close the composer, we can open our terminal. First of all, I'm going to run. The composer's a composer in stole and up will. Obviously, we haven't got any dependencies at the moment. We will install in just a moment, but this will generate the vendor directory. If I just go back to project, you can see it generated the vendor director with the out of older. If we go back with Terminal, next thing we want to do is install our NPM dependencies, which will be pulled from this packaged adjacent sor np install. It will take a little while, so I'm just going to polls this video and come back to you once oldest has been installed. Now this is completed. Sophie just cleared their screen commands K on a keyboard, by the way, not don't feel intimidated by all these things that I've just done, basically composers something that we will be using pretty much throughout this course. But gob, you can pretty much remove this entire file basically as well as everything that's inside of this directory. Apart from the data that SQL, which we will be using and just create your own CSS farms for styling and javascript, just make sure that you include this coal to display Guinness's de select exactly the way it is. That's always basically need June discussed and obviously make sure they include this city . Select blogging within your index, um, structure as well separately, in that case, obviously, because at the moment we just pull it directly through from this note modules through the Gulf violence, all compiled into a single file. I'm just using this approach because I like everything compiled and that sort of things. And this is pretty much the the cassette of structure that I'm using with my projects. Okay, so we've got old is ready. The next thing we need to do is to install a few composer dependencies. So let's go back to our browser and let's navigates two packages that ORC packages don't work there again. And the package we're interested in is called illuminate H T T P. There we go. That's still one that's there. Does the package down a lot of all users as well. So if a copy Dis composer required a minute Asian P, we go back to our terminal based it. Just make sure they obviously call all these commands from within the root of your project , which is this advanced search from PHP. If we return, this will install this package as a dependency for our project that's now been down. We can clear this screen Command K again, and another package that we are interested in is called and it's actually package, which are Britain's bastion. Selenski Adult E N. V. It's based on focus PHP. Adult envy packages go some additional features here s O if we just copy this composer require, and if we go back to the terminal, he to return again to install this dependency, the next one will be PHP unit. So PHP you need. There we go. That's the one again. Let's copy distance I comment, pasted in heat return to install it and once this has been installed, actually wanted. This is installing. Let's go back to the browse and look for another package, which is called Fake F's. Set a out. Those that was the one EVs set any noto for a slash faker. That's the one we need. So we copy this command as well. This is still installing speech be unit and all its own dependencies. Eso Let's pose the beautiful second and I'll get back to you wants all this. Actually, we don't have to. This is now done. OK, so it's clear the screen pays the command hit return and installed a faker. As you can see, I was quite quick. Ashley Command K to clean the screen and let's move to the next video 3. Environment and PHPUnit: Okay, So the next thing we are going to do is to create that adult Ian V far. We just right click file dot envy and what I'm going to do A set a few environment variables here. 1st 1 will be up on this court envying equals, and we going to set it to development. Then we are going to have DB on this court connection, which we're going to set to my SQL for now. Then we actually let's group this database related ones together. Then we are going to have DB on this co host, which is either local host or simply 1 to 7001 which is basically equivalent of local host . Then we have DB Port, which will be default 13306 Then we have DB database, which will be called books DB User name equals Homestead, in my case, because I'm using Home state so the user name will be homestead. Obviously feel these in with the values dots obviously reflect your own local environment, and then DB passwords is going to be simply secret on my homestead insulation. Okay, so now that we have got e N v for the good thing. What now? If you open, I should get ignored. You'll see that this file has never sent to the repository. This fire is always going to be ignored. But if you want to install this project somewhere else, it would be nice to have the example. One which has a copy of all the variables, all these variables, but without associated values. So what I'm going to do is basically copy this far solid. Just copy it and I'm going to call it. Don't envy dot example. And there we go Now, in the example. What? I'm going to do this. It doesn't matter, but database, name, user name and password I'm going to remove the other bits can stay because they they're not sensitive information at all. So now this dot E a n video example is going to be pushed to them repository while this e NV, which active stores this sensitive information like database, user name and password, will not. So now that we have this set up, we cannot close it. So this part is done. So the next thing will be Teoh. Prepare our tests directory. Let's create a new directory here on the route off a project called Tests. And before we do anything else, let's open our PHP uni dot xml. Let's have a look at what this far contains. First of all, it has. This obviously tells us that it's an XML type of the file and the first item on the least backup Global's Wen, set to false disables global variable backup and restore operations for all tests. Then we have backup static attributes. When this one is set to false, it disables backup for all static property values in all declared classes. Then we have a bootstrap, which tells us which out a loaded to use in order to be able to love the classes were going to be testing. Then we have colors to display output off the test with colors such as, for instance, green full test out past and red fall failures. Then we have convert arrows, notices and warnings to exceptions to make sure that we can handle them as exceptions rather than arrows and so on. Then we have process isolation, which is also set to false to run old tests in one PHP process rather than each one separately and Then we have stop on failure to make sure that once one of the tests fails, no for the tests are executed. Otherwise we could end up with a very long output in the terminal window. Okay, The next thing we have here this directory which is basically pointing to where our tests will be stored, which is full stop relative path to our tests Director, which you just created. Then the basically director of our classes will be stored, which is this up director here. And then we have within the PHP section, we have environment variables which, as you can see, if we just opened this e n v file and I'm just going to split view here so we can compare them. Let's close the file browser. You can see there reflect back their environment variables that we have within our dot g and V for the up underscored the envy which is going to be overridden. And rather than having development or anything else that you would put with this as a value for this variable, it will be changed to testing than db Connection is not going to might be. My SQL is going to be sq light and DB database for rescue light. During the test, we're going to use memory. All of the database associative interactions will be done in a memory rather than using any particular database. All, oh, file. And then we have a TV host and server name we have both because depending on your server configuration, use every my use one or the other. And we said them both to local. So later on. And I'm just going to type it down here when we actually right in the test to check if there if the u. R l is exactly what we expected to be, it's basically going to use this locals host for So, for instance, we going to be competing against http colon force left for us like local host. And then whatever else we expect I within this you are. Well, if you want to change it to anything else, make sure that whenever we going to be writing tests, you use the same thing. So let's say you could use assess the tutorials and then obviously within our test, when we going to use this local host, you just change it to us of the uterus or anything else. But don't worry about this for now. Obviously this welcome. A little bit later on while we right now it s so that's our PHP unit. I'm just going to open them ATF eyebrows again. Let's close this file and within our where. Test the directory. Actually, before we do this, let's open the terminal again. And where obviously we are inside off the directory at the root off project. What I want to do first is to check whether you have PHP units installed globally. And there is this way to do it is basically type PHP unit space hyphen, hyphen version. And if you get the version like I did here, that means that you can call it from anywhere within your system. That means you've got PHP unit installed globally. If you don't check Thea other course of where'd you mentioned several times? It shows how to do it. Otherwise, you can just go to PHP you an adult d e and check the documentation A. Otherwise, if you don't want to install it globally because we've included the PHP unit as a dependency, you can see we have PHP unity. You have this being director and a P H P unit is in this director. So what you can do instead, if you don't want to install it globally, is too cold. Bisley Vendor Bean PHP unit. And this will work the same way as if I was in mild environment. Just calling be calling Ph community if I had returned. Obviously I get notice executed because there are no tests. But now I've just called the PHP unit, which is inside of the vendor being rather than using the globally installed one. Okay, so we're all set with the PHP unit now inside of the test directory. Let's create the new PHP class called test case. And if we return, it's going to be a nap struck Klis, which means obviously we cannot instance she ate it from anywhere. It can only be extended, and it will also extend that PHP you need on the skull framework test case. And for now, that's how we going to leave it. So this is the file, the or each off our tests will extend. So if we have anything common that that we want to art here, basically, if you want anything that will be shared. Ah, with our tests, we can put directly nous farm, and then that's going to be available. Using any methods will be available to all of our tests. So this is our test case. If we close this final in order for us to be able to use it without tests, we need to outer loaded because it won't be out a loaded automatically. Like our tests, which will end with the test in in a class name. So if we need, we need to open to compose it with Jason. And after the first outer low block, you can see the require section has been automatically added when we require dependencies fire project. This illuminates actually being Dottie envy, PHP unit and faker. This has automatically not here. And the new section here will be called out a load death for basically things that we want to out a load while in development. Ah, moat. Okay, so, uh, the the entry here will be class mop and we want to mop the following classes. The file it within the test directory, which is called test case dot PHP to does the far we want to load. Actually. Rather care Lee brackets here. This is theory. A off different class classes sold. This needs to have justice square brackets John Kerry wants. Okay, so that's all for now. We cannot safe and close the file. One last thing that we need to do is to run, compose. If we go back to a terminal composer dump hyphen out or load. Which old flak? So hyphen. Oh, for optimization. Make sure it's optimized and it generates the new outer loads file with this test case now included. Obviously, if we type, I just clear screen here. BHP Unit and he returned. We still get notice because there are no tests. So let's move. Next video. You right in the first test and implementation for our database rubber. 4. Database manager test: in this video, we are going to start working on our database component. The first thing we need to do is to ride a test under the test directory. Let's create a new one called Unit for unit tests and then another one called Database, where all our database associated tests will be. Ah, start. And the first test we're going to run is going to be called database manager test, and it will test the make method on the database. Managed database manager will act as a factory basically to returned the correct instance of the databases, depending on what we have within our e n v. File. How we said the connection, whether it's going to be my ask you. Well, all sq light database manager will take care off, basically returning the correct one. So database manage the tests that we are going to write is basically going to check whether it returns the database instance. So we are going to called our test If I just public function returns on the school database instance and we need to our dog block here test this tell speech. But you need that this method is actually a test and it should be executed and obviously test. It's using whatever method we going to use, uh, within ah, and the method we are going to use is going to be this assert instance both. But as you can see, my ideas highlighting is because we haven't actually extended the test case, which then extends this speech be unit framework test case. So what we need to do is extend and then test case. There we go. That's what we need to do. And now that should work fine. Obviously, this methods takes two or three arguments. The 1st 1 is what we expect to be returned. So it's going to be database colon, colon class. And then the next one is what is going to return this specific instance in our case, Yeah, which is going to be database manager, class and method make. And then the third argument, which is optional, is the message that we want to display if this test fell. So it's easier for us to identify basically which test exactly felt and I'm going to pooled in double quotes. Database manager Colin Cold make did not return instance off database, and that's it. So if we now go to our terminals at this, our first test. If we go to terminal and call PHP units from the root of Ire project, you'll see that obviously this fails. It tells us there is a narrow database manager not found. We don't see this message, which we just typed here because that's not actually it doesn't even get dead. It's it's it's actually telling us it's a narrow because we a call. We are basically calling something that does not exist at all. So I didn't even get to this third argument. Okay, so what we need to do first is obviously create this database manager. Let's go back to our anytime and under the up directory. Let's create the new directory cold database. And inside of these director, we're going to create a new class called database Manager, and the name space for this class will be up box slosh, then database, and that's it. Every click on. OK, now let's just close all this. We don't need all this. Create it. Ah, and inside of this database manager, we need the make methods of public, and it's going to be a static function because we calling this? As you may remember, for just go back one. You can see we are calling this make method statically with this to Collins A and the name of their methods of make, and it will take two optional arguments. 1st 1 will be a driver by default, nor, and the 2nd 1 will be off and the rate type, which will be called options, and it's going to be an empty rate by default. So if we know save it, go back to the terminal Ron PHP unit again a z can see still Texas that it cannot find database manager because we didn't actually imported here. Sold. What we are going to do is use the use statement and then we go for up, uh, database and database manager There you. So now it should find this class. So if we go back to our term, no clear the screen commands K BHP unit and there we go. So now, as you can see, the year has changed. We have data His major test of tens database instance PHP Framework, exception argument one No value off PHP framework as it are. Set instance off Must be class or interface name. And obviously this is the air because we get in this era because obviously the database class does not exist. I'd So what we going to do next is cleat. Create the database classier inside of our database directory. So database and the name spaces correctly fashion already. So that's what we need. Let's just close this and remove that we have database class now. This one will be in abstract less. So that's quickly repent up Struck because we won't be instant sheet in this database class on its own, it will have extensions like sq light and my SQL eso before this. Well, it's just important as well. So up, database and database. There we go. If we now go back and Troy in the terminal for clear command K and now we're on PHP uni dairy. Go. Now you can see that the message has changed. Now it tells us that it felt a setting that Noel is an instance off class database. And now our messages you can see is now displayed here. So whatever we put as 1/3 argument here, as you can see, database manager make did not returning stars of database is now displayed, so the problem now is the fact doubts our database manager dozen return instance off database doubts does basically while it's failing. So if we go back to our database manager, we obviously cannot just return new instance of database because it's an abstract class. So what we need to do is to create drivers. Basically, I'm going to call it drivers, but it's basically the extensions fall for this database class. It's going to be the sq flight on my SQL. So inside of the database directory on the hour up dietary. Let's create a new one called Driver or you can call it really whatever you you you like. But I'm just going to call a driver. Okay? Inside of this drive, I'm going to create a new class PHP class called my s. Q. L ask you, l there we go and it's going to be under the name space up Ah, database. And then it's going to be driver. So that's one of them. And if I just clear all this again and then another one will be sq lights or s que light and the same name space, it's all good. Okay. Both of which will extend database the abstract database class. So if I go back to my SQL do the same here, extends database. There we go. So what I need to do now is simply return. Let's say new sq light and that shoot make the test pass. So if we go back to the terminal, clear the screen PHP unit. And there we go. We've got one test and wanna session. As you can see, this colors are setting. Tell regarded already he's highlighting, disagreeing, telling us everything is okay. So we got this test which we've written inside of the database manager test is now passing . But obviously that's not quiet when we need, so we going to have to dig a little bit deeper. But for now, this database manager test returns what we asked for. So it returns the instance off the database class days, test passes, and we can now move to next via 5. Database drivers: in a previous video. We've created this first test that asserts that Thea Object returned by calling database manager make method is off. The instance. Off database we have returned are simply new instance off sq light class. But as you may know, because we are extending database, that's why we can test it for ah, basically instance off the class that it's accents, it could also, we could also check the same way if it waas implementing any interface, then we could check if it's instance off this interface. But in our example, we are only extending the date of his class. And that's why we testing for this and this would apply to any other driver class that we will be writing. So basically creating a class the test starts actually test for the class. That both all of them actually will extent is a little bit better than writing test every time we are actually going to create a new implementation. Okay, so we've got this desk and let's now go back to our sq light because obviously at the moment this class is of no use to us, it doesn't do anything. It's just a blunt class the same about a database inside of the the abstract database class . What we are going to do is create a protected property called PDO. And it will be if I just put there, doc block above an instance off PDO object. I'm just going to imported. So use PDO. And if we go back to our sq light class inside of this sq our class, I'm going to create the constructor, some new constructor and this constructor will take two arguments, the 1st 1 being the name of the database. So we just call it database, and 2nd 1 will be off the rate type and will be called options. And let's just update dog block. So we've got Parnham's oddity as well. Okay, inside of this construct of what I'm going to do is instance she ate this PDO objects PDO equals new p d. Oh, there we go. And it will say for arguments the 1st 1 and being a data source name. So sq light is the type of the database we're going to be dealing with colon, and then we're going to concoct innate it with the database name. Then 2nd 1 is the user name. So we set it to no passwords set to Nola's Well. And this is because SQL I does not use user name and password. We simply set write permissions to the file by sick database file, and that's it. And then the last one will be the method we going to call the methods, which would create in just a moment called construct options. And then we go into past our options argument through and let's obviously semicolon. After all this, let's import this video as well. So we have it right about the class definition. Eso that's our sq light class construct completed. Let's now go back to the database and the first thing before we. Firstly, before we create this construct options method, I'm going to actually create protected property called default options and for default options. We're going to create an array and disarray will contain PD. Oh, constant cold attribute from air. Um, also I d d. On the skull era malt Dan, we gone to associate PDO another constant air mold exception. What does this mean? Every error converted to the exception, in other words, so we want to deal with the exceptions We don't want to handle errors. We just want to deal with the exceptions in any exception way. Okay, so dance. Let's just run the dog block here again. This is in the race, so that's fine. And this will be always part off their of the options. The fourth argument for the PDO object in the same instant station because this construct options will basically up end to it. Eso if we just copy the name of them method again from sq light. We can now create this new protected because we obviously need to have access to this method from within the classes that extend it. And then it will take one argument, obviously array options, which by default, will be an empty rate. Okay, and now are we going to do is check if empty options, then are we going to return? Is this default options array? So that's all we're going to return. But if it's not empty, then we are going to create a new variable called option new options, which will basically be a copy off this default options array. So it becomes an array, obviously. And now what we want to do is to merge this array with this one. Now, the only problem with a rain marriage, which is what we could use is that these constants. If I click on that one, you'll see it represents the numerical key. And when we doing array merch with America Keys numerical Kiss s index is off the array. They will not be over written. So any item If you wanted to override this item, for instance, with anything else, then we wouldn't be able because their numerical virus. That's why we need to use the four each statement. So let's use the for each options. Ah s key equals option. And when we going to do here is basically new options and then key equals option. Obviously this time, if we were to use the same constant name for the key when we passing the options as an argument, then it would overwrite it with a ray merge. It wouldn't it would upend to this array. And this way, obviously, as I'm saying, we could override any key whether it's string on numerical value. Okay, so now the last thing that we need to do is simply return new options and not so So now this fourth argument here construct options will take the second argument, which is off the rate type, and it will merge it with default options. All potentially override anything that's within the default options. Property by default. So now the last thing we need to do is to generate their dark blocks so we know what Parnham's it takes and what would it, what he would change as well. And let's put some description. Mergers, a cone mergers. Constance tracked options. There we go. That's all done. If we now go back to a terminal, we've modify. Query. Coty Asa, Let's Ron pH units see what's happening and we have an error. It say's doubt. Database manager test returns, database database. Instance Methods meeting argument 14 sq light constructor. And that's right, because what we doing at the moment if I go back to our coat, our editor, we've modified the sq odd we've under the constructor, which requires the first arguments to be present. It doesn't have any default value, but our database manager only calls there. The sq light creates a new instance off the escalator without passing anything through. We could obviously put something statically. Yeah, let's say database event something like this. If we go back to our team, you know, if we refresh basically around the PHP unit again and that will return Green, everything's fine. But it's obviously not right. I'm just going to clean this terminal window. Yeah, that's not how we want this to work. You want us to be more dynamic, Want to be able to basically specify what they to be base we want to use and what credentials potentially should use from within this dot e N v. Five. So let's now focus on this database manager. What we are going to do here, we taking two arguments. These options will basically be passed A second argument to this constructor, which will then be passed to the PDO constructor. But the driver will indicate which database connection we want to use. So what we are going to the rather than returning this sq light here, we're going to start with If is no driver, then what we are going to do is override this variable drivers Now driver argument will become adult E N v. We using this dot envy package, get method on it to get the specific value associated with the environment. Variable, which was declared inside of there, don t envy far, and this one is called DB on the skull connection. So if we don't pass any driver through if we dawned, strictly declare which driver want to use. Check their dot envy file DB Connection. In this case, it's my SQL. But as you may remember, when we're looking at PHP unit XML file our configuration. We are overriding this while we testing to ask you light and in database we over rights to memory. It's to run older tests on database in memory rather than using any files. So we are now using this if we don't specify strictly which driving want to use. But if the driver has been specified, what we want to do is of return. Actually, either it's been specified or not, we are going to call. They give a method. So return coal user funk. And now we need to specify where cola Ble instance in our case is going to be new static, referring to our database managed to itself. In other words, we create new instance and then method on this instance driver driver. So basically, whatever is going to be associate it with dis variable, it's going to represent the method name. And then what we want to pass through as an argument is options. The second argument we passed, it does make a method. Okay, obviously, if we try and test it again, it's going to still tell us that we have a problem here. Because of the college that Funk expects. Paar Meter to be a valid callback class database manager does not have a method sq light because we in a test mold, it automatically picked wherever db connection value it has associated with rather than taking the life environment here. But it's not a life environment by bicycle directly from the dot N V five. Okay, so it tells us that sq light method does not exist. Let's quickly create this method, so we're going to create protected static, a method called sq light, and it will take ray options again because that's what we're passing through to this coal and let's stop here and it's create stray away. Another one protected start IQ function, my sq a. So weak over both of them straight way array options and then empty rate. Okay, so now we have the array. Let's quickly go back to our terminal PHP unit. Now we have different exception. Different error here by six. Database manager make Did not return instance of database. So basically, we going back to where we were in a previous video where while we were calling this make method on database manager, we didn't get the database instance. So what we need to do now is return new sq light, which which is what we did previously. But now we are going to pass the arguments. The 1st 1 will be dot e n v get and we take in the DB under skull database. Instance bisque name off the database run in semi colon coma and then options as thin Second argument options that we as the second argument. Eso No, If you go back to masculinity, concede database was name is the first argument. Second, is this options that is passed later on through to this PDO, uh, class by saying this instigation of the PD object and if we go buck so that should presumably solve the problem with the test. If we go back clear the screen PHP unit And there we go tests pass it. But now it actually uses the proper code the code that we are going to be using the production environment in other words, in life environment. So it doesn't return the escalate instance where we automatically instant she ate the PDO So all this is passing now let's do stray away the my SQL one as well So my SQL rather than actually doing this. First, let's open my SQL and let's start with this one. We're going to create the constructor here as well. So let's create new constructor and the constructor will take a quite a few arguments. Yes, so we're going to split into separate lines. Database is going to be the 1st 1 Second one will be host, which by default will be 1 to 7001 which is a local holes. In other words, then we are going to have port which by default will be 3306 Then we are going to have user name Den is going to be a password. Quiet a few arguments, as you can see and then the last one will be options and it's going to be an empty array to start with. Let's create their let's create the dog blocks of the dog. Looks rather there we go. So all these poems are now at least there. And their next thing is we going to do is to do exactly the same as we did in the sq light . Ah, class constructor, which was instance she ate the PDO object. So new p d. O. But this time we going to have quad a few options. I'm in quite a few options. We're going to have this user name impossible added to it, and the first option will be my SQL Colon. And in DB name equals fashion. Let's use double quotes so we can put the variables directly in within the string, and I'm going to rob them with curly brackets. So database. Then we have colon host equals and in between a curly brackets, host Dan colon port equals and port. And after this comma and then we go for user name, second argument, password, third argument and disk unstructured options. A. But instead of passing the options tray away, I want to add one construct one option to this to these options automatically when we dealing with my SQL. So what I'm going to do is create another method, which I'm going to call straight away here called Paris Options. And then I'm going to pass options argument to it. So this is going to be the construct again. I'm going to import this PDO here. Also, it's above declare clause definition and, let's know, create this parts options method, which takes array, which by default might be empty and inside of this method, we're going to start if exclamation mark a ray Key exists and we're looking for P. D. O Call on column, my SQL our tribute initial comment that still one and then inside of the options argument. So if it does not exist, we're going to add it there. So options. And then let's just copy all this and this will equal to set names ut f. Eight. I want to make sure that everything while I'm connected to the database everything is executing using that utf eight Harter set. You can obviously change it to whichever are the hard to say you might be using for your own project. But utf eight is the one I I will be using. Okay, then return options. And that's all we need to have in this method. Let's create dog blocks again. And let's put a description Art options to PD all construct er nothing that makes sense. Okay, on now, here. Going back to this one. That's quickly. Ah. Specify what sort of data type we expecting here. Database argument will be of a string types of string. Then host will be either a string. Yeah, it is. It is going to be a string. Then we have ah, port, which is often interject type. User name is going to be string as well. Password is a string as well, and options isn't great. Okay, so all that's updated if you run our test. Obviously what we've done, he hasn't isn't changing anything, really? So if we don't test, we get exactly same result because I've seen we are using behind the scenes sq light while testing. So this my SQL isn't going to be used while we testing this line. I think that sits so going back to our database manager. What we need to do now is for this my SQL one method we are going to return new my SQL. And now we need to provide all these options and I'm going to split them all onto new lines . So if we do like this, uh, okay, allow, let's indented it and semicolon a d And so the first argument will be dot e n v get methods and we want to get value associated with defy able db database. Next one is going to be adult BNV get and we want to get DB on this girl host Next one will be adult e n v get and it's going to be Port Deby on this core part. The next one is dull T E n v get and it's going to be DB user name and actually we have more. So let's just duplicate this one password db sward. And the last one was options. So options, There we go. So you have 123456 arguments. Quiet. If you buy that stuff, should be working fine here for this specific example. Okay, So if database host port using impossible and options that just go back to my SQL database whole sport, using them impossible and options at the end. Okay, so that's all fine. Let's again generate dog blocks here for all three met. It's, uh let's start with the one. It's all, um uh get database. Instance. Next one, this one we can call get sq uh, light Instance. And then get my SQL instance Can get my esque Que el in Stan's. There we go. So that's so done. Ah ah, Where database manager is now completed. Uh, our database manager, I don't think we need any more tests here. We only need to make sure that we get the database instance, and that's what we've tested for. So we can now, for just check if we've done everything it my sq Well, one is done, sq Light one is done as well. Database, obviously, is something we're going to be working on in the following video spot. Database manager Far can now be closed and database manager test also. So in the next video, we're going to be adding to this database class. But before we do this, let's clean up a little bit on the left hand side here. We don't need this database which was created when we call this escalate with just a static database. Name eso. Let's remove this file. Let's remove this license and read me as well. These are not the funds that we need here, and I think that's that's a bit better now. Okay, let's most next year. 6. Database execute method: So now let's continue with our database. Absolute class about before we write any feather methods. Let's go back to our test unit database in creating a new test. This son, we going to call it Database Taste desk. There we go. And what I'm going to do is this one. We also extend test case. There we go. And the first thing I'm going to do is to create the private property called DB, And what this property will represent is basically the database instance on Let's import he as well that we go. So basically, this DB property well represented database object The first test that we are going to write is going to be called It is obviously needs to be a public function, creates new PDO instance and executes simple query. So basically what we're going to do is create a new instance, are using the database manager, So let's quickly do this. This DB equals database manager and we want to use the make method and also we need to do here Bicycles database manager takes care off, generating the appropriate, um, database object, whether it's sq light in our case on my SQL, obviously now, a case is going to be escalated because again, if we go back to PHP unit, that's what we've specified here by sea for the DB connection, we want sq light, so we should have sq light associated with this DB property. So next, now that I've gold, this database instance here what I want to do with this database instance of this DB instance is to execute the following statements voiced in select marks one comma 10. So this should return the maximum number out of these this range bicycles. There's going to be between one and 10 and 10 is going to be there. The maximum s So this statement should return 10 and I'm going to associate it with the variable cold breeze sold equals. And now what I'm going to do is to use the assertion. So this assert equals 10 and the result. And again, what I'm going to do is provide the third argument for this method. If we just put on separate lines and ah, the message, if it fails, is going to say query returned Incorrect Mark's value. Okay, now, obviously Ah, database. Our database object does not half execute method yet. So what I'm going to do basically up before we actually run any tests? Let's indicate that is attacks to by adding this dog block here as well. So test that we go. And now for go back to Terminal Ron PHP unit. There we go. And obviously we have an error here, which tells us that coal too undefined method execute on sq Light, as you can see, tells us that this DB property is actually representing SQL I driver eso. Let's go back to our editor and what we are going to do now is basically create this execute method. So database ph. B and after our construct options before we actually create this execute method, what I'm going to do is create another method called set attributes. It's going to be a public function set, are viewed and it's simply going to take to art to arguments. 1st 1 is the attribute and the other one is going to be a value and what it Wilders basically delegate the coal to the same method. The method with the same name on our PDO objects or set attribute an attribute and value in there we go so It's basically whenever we gonna use, say, our database instance, we can use the set attributes to set any attributes on the PDO object. Let's just create a dog block for this method as well. And what we are going to type in here is basically delegates. They're like gates, a method call two under lying p the object instance methods. Let's put it like this. OK, so this is just just like a simple help A method cat basically to be able to access to set attributes on the PD objects. Okay, so our execute method now. So we're going to start with the public again because we need to be able to access it from outside of this object and method. Coal name is execute and it takes it will take four arguments. So that's bicycle girl that two brackets, I'm going to put them on separate lines as well. 1st 1 is going to be about SQL statement. 2nd 1 will be array off para meters that we want to pass to our where, together with a statement, basically because we're going to be using their prepared statement to make sure that obviously we are safe for any sort off SQL injection against any SQL injection and then we give the third argument is also an array and is going to be a driver on the skull options in case we need to pass any and then return True whether we want to basically return. Ah, the result. Or we'd like to return the statement and change it later on. Eso First thing we're going to do is create a viable cold statement and this statement will be simply this statement and we pass SQL and driver options to it now. We obviously haven't got this statement methods and it's quickly created as well. So our method and this statement method will be a private one because we only going to be accessing it from within This, uh, this subject this class, okay, and this one takes obviously to arguments. Now, 2nd 1 let's I painted with array and by default, it may be an empty race, so we know it's not the required argument, okay? And never go full statement equals and it's go for this video object and we're going to run the prepare method on it. Passing the hours, SQL statement and driver options if there are any. So we prepare in our statement for execution and then we'll be checking if if exclamation mark checking if statement evaluates to Boolean falls because of this exclamation mark, then we won't throw new P d o Exception. And this PDO exception will say query statement felt. Okay, let's make sure. Obviously, this PDO exception is also important right to the top. Okay, so basically, what we're going to do after oldest simply returned a statement. So what this method does we could pretty much put this call directly here and associated with a statement, but then would have to do manually this check if it evaluates to false basically and then throw the exceptions rather than doing this every time we going to be using the statement as actually prepare method on the PD object. We just have the statement method which does oldest basically executing their prepare method and then checks if it evaluates to true or false affair values. The falls will throw the exception. So we've got everything we buy 60 separate this concern into a separate by putting this into a separate method and now we know that this statement method definitely did not evaluates to false cause. Otherwise, obviously, the speedy our exception would be thrown. And in fact, it will return the PDO statement. Ah, object instance. Okay, so the next thing So that's basically everything within this statement method. Now we can use this statement within our execute method to call the execute method on it. So what I'm going to actually do rather than just call it directly on the statement, I'm going to associate the result which will be of a bullion true or false with result a variable so result statement and now execute. And we're passing through our para meters. So basically, statement runs the prepare method. So we pass into the SQL with any sort off placeholders and driver options if there are any and then we passing partly to separately to make sure that obviously we we are doing this in two separate wastebasket binding a separate from the statement itself off to ensure that we don't We are basically okay for any sequel injection. Okay, so now results stores bullion, truffles. Now this return fourth argument comes into play. Now if you want to return stray well, straight way true or false. After this execute, then you can do it. So we're going to check if return so not result every turn. Then we simply return result So we will know whether WAAS actually execute successfully All it felt otherwise. We simply return statements so we can either. We can basically chain further methods on itself. There's anything else want to execute on this statement? Instance. Weekend. Basically, if it will set to false OK, so that's our execute method. Let's now aren't dog blocks as well to it execute and statements to new methods. So for the executes are what we are going to do is simply, say, execute SQL Statement and fold them a statement. Um creeper SQL statements. It's now. Yeah, let's go like this. That's fine. We can Obviously, this is We can import this PDO statement because the statements about representing the PTL statement instance object instance so it can import it as well, and the same Here's okay because it's either bullion if we decided to return it straight away, is going to return Boolean true or false after executing ah, this execute methods on the statement. Otherwise it will return video statement. Okay, so our execute method is now ready. Let's go back to a terminal and try to run the comment again. So PHP unit and let's see if we are passing and we dio. So we've got two tests to assertions. We can now safely use this execute method to run any queries basically directly on this database object instance. 7. Inserting new record: in a previous video. We've created the test and implementation Fall the database Execute method. In this video, we are going to create 14 in certain records to the database. Now, before we do anything, what I want to do, because we are going to be using this database instance throughout this test by city for pretty much with every method we going to create he every every test. So what I'm going to do it it's is basically this instant station needs to go to a set up method and set up method. If I just click on this test case, which we extending from within the database taste and then for the speech be framework test case. And if I look for set up method, you'll see this is an empty method, but it allows what it says. Basically, it sets up the fixture. For example, open a network connection. This method is called before a test is executed. So every time we run each of these tests from within any of the test class, this set up is being called. So what I want to do is basically create override dis method, so protect it function set up, and what I'm going to do here first is to call the parent once a parent set up. So if there is any meth, obviously we know that the within this BHP unit from or test case it's just an empty set, our method. But if you wanted to create one, sets up method for all of the test, let's say we want to do something that old tests require before each test. Now we could add it to the state's case class. But obviously, for the time being, we don't need another set up method here. We only need one for them for a database test. So what? I'm going to do its move. This instance. Station off the database, object to our set up ones. The part and set up has been executed. This will also be executed, and we will have database instance associated with our private database property. Okay, now, obviously, we can probably rename this method because we no longer creating updo instance. So it's just remove this part and leaves a reliever only wait executes same book wearing because that's what it pretty much does. So next method we going to create next test is going to be public function and it's going to be called inserts new records. There we go and it's tray away indicate that it's a test. I'm just going to scroll up a little bit. So it's a test and I'm going to create a few new lines here. And the first thing I'm going to do is create the result variable and associate it with whatever the method called art book method, which we don't have yet is going to return. And then I'm going to run my assertion. So this assert true and we passing. The result through is an argument, and the second argument will be the message saying that insert state meant failed and let's put on tune your lines. There we go, let's know, run the test PHP unions And obviously we fell because this art book method does not exist in a callous clear it go back to the yet itself and what I'm going to do now is, rather than other this method directly into our database test file. I'm going to create a direct occult traits under the unit directory and extract all this help of methods which are interacting with the database into its own trade. Cold. I just greed and you file cold book store that we go and what I need to do is before we actually do anything. Let's open composer Jason and added to the outer loader. So what we have here is for the class mop. We are going to out tests for its lush. You need four slash traits and we have book star dot PHP so that I can be out a loaded now . Obviously when I need to do is go back to that, um terminal and run composer dump Ah, hyphen Our tall load and let's run it. Optimize So under. Sorry, hyphen old. And there we go that generates optimized out of Lord file. So now this bookstore is going to be included in the outer loads. Okay, let's go back and bookstore What we're going to do. Obviously that's not a class that's a trade. So let's change this, And the first thing I'm going to do is to our this protect it function called Art Book, and it will take array as an argument, which is going to be called user under skull data by default empty and And the first thing I'm going to do is to check if this db which we going to get from whichever classes using this Methodist straight insert method. Obviously, we know this incident does not exist. Let's create a new line. And within this inside method, we going disinterred method basically will take two arguments. 1st 1 will be a table name. So it's going to be in this case books and the 2nd 1 will be the data that we are passing through. And to pass the data, I'm going to use this and book data and then for this book data mated, which does not exist. Obviously, at the moment we are going to part this user data. So basically this book data met, it will have some pretty find It's going to return in the ray. Basically, it's going to have some pretty find finance associated with the day bicycle, the database table fields. But if we want to override any of these default ones, which will be basically fake fake values, we can use it by bicycle parts in this argument to this art book method and override them this way. Okay, so here if it did. If Inside returned true, then what we wanted to do is this last insert i d equals this db last insert I d. What we doing here? We obviously need to underst property. So it's art. It's quickly. He had It's open. It's going to be protected. Last insert I d. And it will be off the indigent type. Okay, Also, dance this one what it will do Basketball office Don't have this last insert I d i Them on this database object yet We will create it a little bit later on what it does. Basically, once we've inside the record, what's there? Last I d off this rig was the idea of this so we can later on compare when we do in any assertions within our tests, whether in march is the i. D off the record that we were helping to art No update on the babies in this case of this article, because inside will return this last sense of I d S. O. And after that, obviously we return true because this returns true NFL's first place. That's what we were able to actually associate this the result of this last instead, I d with the property last things, that idea after oldest after this, if statement return falls because obviously if it felt that's what it would return in the first place. Okay, I'm going to art Dog broke here as well. And what we're going to do here, let's say arts, uh, book record and that's pretty much it. Now, one thing we obviously don't have is this book data about data. I'm going to store separately. So I'm going to use another trait, and this straight is going to be called because we're going to be using this straight in other tests as well. This one is going to be called model data and inside of this one and again, that's a trade. So trade what I'm going to do before we do anything, I'm going to go back to this bookstore and make sure that we using the Straits or use Modell the user use model data. There we go. And now this one will have this book data methods. So let's go back to this model data and what I'm going to do here. First of all, I'm going to create this method, so protect it function book data, and it takes a ray called user Data by default Empty and let's leave it like this for now. We will work with this in just a moment. But before we do, what I want to do is to create a new protected property cult faker. We said it by default to know. And then I'm going to create a protected function but new method called faker as well. And we'll check here if ISS know this faker than what I want to do is to do basic being instant. She ate. It's a faker equals factory, fake a factory, create, never go and that's all I need's and let's import this factor. Obviously, this is one of the packages were installed earlier, and now we're going to simply return this faker property. So we always by calling this method faker, we always get instance off the fake. In other words, okay, soul again, Let's put the dog blocks here, and this one here is not gonna be just know, Let's do it like this or no oh generator. Because that's what we expecting it to be by default. Seasonal, obviously. OK, and then what can we call this. Let's get, um, Vacher instance. And this one will be Get book data. Okay, um, inside of this book data now are we going to do? Is And again, I'm going to create a few new lines. I can see. Let it about inside of this book date omitted. I'm going to return. This'll merge, date up methods and this merged data will take toe art to a race by sick to arguments. 1st 1 is theory that we're going to generate using faker and the other user data. So if we want to overwrite any of the fake data, we will be able by passing this user data argument. Okay, let's create this. Merge data so protected function merge data, and it takes first ones array data and second ones also ray user data by default Empty. Now, this merge data will first check if isn't empty. User data done. Merge it with the main data erasure. Data equals array, merge data and then user data. And after oldest, let's return data. So, basically, we're going to create some fake values here, some testing values, basically as the first array, and then we're going to pass the second race. So if we want to overwrite any off this will will be able to buy passing this argument. If user data is not going to be empty, then basically user data in Texas will override the ones that we've set using faker here. And then we're going to return the rain. Okay, And it's going Teoh override them as long as they going to be string indexes obviously again. Rain merge. If if the the indexes are off the interview type, they will be appended to this area. Okay, eso for the fake data. What I'm going to do is start with the category I d Field, which this ah books table will have. And we start with this faker and number between, and now we're going to have a number between one and 10. Uh, it's basically going to represent the i d. Off a category to which, with which book record could be associate ID. Now, if a cave and if you know from your with a fake Ah, it basically generates our random, basically random strings into jests dates and so on, but anything that you can only imagine pretty much eso if you want to do Iran test is fantastic for testing because obviously you don't always want to be strictly typing certain values fakers going to generate them on the going. And you can basically obviously use it this way so category I did and we have eyes B n which will be this faker and we're going to use eyes be and it's got to 10 and 13. 10 is going to be just find then we have year. We want to generate some year this faker ah year property and then we have title this freak er and we're going to use words method. We want three words and we don't want them as theory. We want them a string so we need to set the second argument as true. Then we have description this faker sentence. Then we have price this faker Ah run dumb float and we want to decimal places. Now before we go any further, let's on the return talk here as well Returns array and let's our dog blocks for this merger data and what it does it murder merges data some age date or simply pretty much the same as their method name. Okay, so all that seemed to be working. Find. Now, if you go back to the bookstore, you can see our book data is now available because obviously using we are using this trait . So book data is no longer highlighted. If you go to the database test, we don't seem to be having access to this art book it And this is because we obviously not using this bookstore. So use book store. There we go. If we use this trade now. Now, if you scroll down this out book is no longer highlight it. I don't We can click on this and goal straits to this trade method. Okay? No, this model dates off. Uh, isn't going to be available until we added to the composer. So composer out all of death with a class mop again. And we are are being this time model data what we need to do. I can now save and close this. Go back to terminal and let's run a composer dump, hyphen out or load optimized to generate a new outer Lodha, which includes these new traits. And I think that's it. If we go back to the terminal PHP unit and we obviously are calling this insert method on the database instance which does not exist. That's why the air and let's work on this method in the following video. 8. Database insert method: in the previous video of Created. This inserts new record test and two trades, bookstore and model data in order for us to be able to insert new record. And if you click on this art book method, you'll see that we are using this insert method on the database object. We obviously don't have this insert method yet, so let's close the strait. Let's go to our database farm. And after the statement, we are going to create a new public method called Insects Off Public Function Insert, and it will take two arguments. 1st 1 will be the name of the tables or table, and the 2nd 1 will be off the You're a type and its simply going to be a data that we want to insert to this table. And we are going to start with the S Q L Variable, which is going to store this sequel statement for the insert. Let's start with insert into and then between them back takes and double and curly brackets . You don't have to use them again table, and then we are going to use brackets and in between the brackets, we're going to wrap each field off the database with these back ticks. And again, this is entirely up to you don't have to use these back ticks. I just tend to use them same as the scary brackets. So your statement may as well be something like this without these tactics, but I do like to use them. So that's my personal preference. Okay, Now, within these brackets here, I need to split the statement because what I'm going to do is s a double quote to make sure that I'm closing this first part of the statement. Semicolon. Then we are going to Concord in eight. It So s Q l full stop equals double quote. This is going to be later after the statement and an SQL con captain eating here, I'm going to implode using the implode function. We are going to implode using these back ticks and then comma in between. And I'm going to show you what the example of what we are going to achieve by doing so and then array on this coal keys and we pass data through and know what's going to happen here . We are going to start. I'm just going to type example statement the statement will be something like this. Insert into and then say table books and we start with the brackets and this implode what we'll do with each item off this array. And obviously we are looking for the key. So if we go into past theory, let's say name equals something. Then we are going to reason this air a kiss that that will return array off only the keys off this given array. So let's say books at name, field owl, thorough and so on. So this is what we going to do to basically achieve by using this insert into them off his back ticks, obviously ending within the brackets, disclosing here and using this implode method. As you can see, this implode will simply create the closing back, tick comma and an opening backed it for the next item of the year age and then ed the end. We will have to close obviously the last one as well with a back kick and close bracket. So this is this part of the statement and then, actually, rather than just finishing it here, we need to our values and then within the brackets now, without the back ticks because we are going to be basically passing through a placeholder zone. Just going to Con coordinated here again closed his Brockett and is going to be the end of the statement. But before we close the statement sequel again, Concord in a Ting with implode again, we're going to become coordinating these things with just come at this time, and the thing we are going to become caffeinated will be question marks, bicycle placeholders for the prepared statement. And this time what I'm going to do is to use array on this call feel, and what I want to do is to start with in the zero. The number off I tempts that I want to use is going to be a count data because this tells us how many items we are passing through. And then what I want to feel this array with is the question mark is bicycle placeholder for our values to be associate it with the keys off this area. So that's what I wanted to serve Isaac. This part if I just again type after this method, it will do give us values and in between a block bracket question mark question mark question mark and so on, Depending how many items we are passing through using this this area argument in this state argument. OK, so that's our SQL statement. Now we're going to check if a low key, perhaps, and an exclamation mark. This executes SQL, which were just prepared and then we're going to pass through a second argument. Array values from this data array argument. So this time, rather than Azaz another than kiss, which which is what we did here, we're passing the values off this array. So basically again, let's just just to illustrate it, If we passed the array off, let's say, uh, name something and then just scroll up a little bit. Title something else, then obviously here, a great case is going to give us name and title airy values. Who will Britain something, Something else. The array off these of these items. Okay, so now we're checking. If the statement did not execute successfully by six of this execute method returned false , then we simply return falls. But if it returned true, then what I want to do first before actually return, because we obviously could just return the statement read this return execute. But what I want to do is if it's successful, that I want to do this last insert on the score i d insert. There we go. I d equals this p d o last insert idee. It will give us the i d off the last record that has been added to the database so we can later on play with this record. If we need so and then we'd return. True. So once we've got all this, we're attention. Now we need to create the property. So let's copy the name of its scroll right to the top. And after these default options, if we create another protected property, last insert I D. And by default, let's set it to know and we are going to are some dog blocks here default. Nobody will return integer. Otherwise, cave was scrolled down, and now that we have this property, obviously we need to be able to access it outside off this class or the class or any class . Obviously, doubts extends it because from directly from this one, we won't be able because it's an abstract class. So let's create another method. But before I do this Let's quickly our dog blocks here as well. And some description Odd new record to the database. Okay, So after this insert methods, what I'm going to do is create another one public function. Last insert I d. And this one will simply return this last insert idea. We just don't want anyone to to mess with this property. That's why I made it. Protect it on. Just give the get a method by six, so we can obtain it. But we can't overwrite it. Okay, so now let's again our dog blocks and returns it into general. No, and description will be Get last insert I d. There we go if we don't try and run the test. So let's open the terminal PHP units. And what we get is a narrow because no such table books exist. And this is because obviously, we haven't done in migration. Nothing. So this is a good time for us to start using this migration component which came with the exercise fast. What we need to do if we go back to the database test after their initiation off the database object here inside off the set up method. What we are going to do is to, uh, in between the the two brackets because we're going to be associating this with any variable property we are going to call new migration manager and this migration manager take takes another argument. New migration for the migration. There we go. This one takes the instance off the database and what we want to do is to call the method up on this instance, bask in this instance off the whatever migration manager is going to return. I'm going to import all these classes here. So if we just imported all the girls and I can see they're all listed right here, okay, If we save it, go back to a terminal. And now around PHP unit. As you can see, we have three tests, three Alsatians, which passed because everything is green. So if we go back to our A database test, we have this execute simple query inserts new record, and then the other third test is inside of our database manager test, which is returns new databases. That's all three tests in assertions pass. If I was to change this to assert false, for instance, we go induct chute fail if we know wrong PHP unit and it does tell that the insert statement felt felt asserting that true is false. So obviously, if we go back to true, which is what it should be, we go back to green and okay, so let's clear this now. Let's quickly have a look at this migration here. Migration manager If we opened this migration manager and the first thing you notice is that has two properties. 1st 1 is the migration, which represents the argument. It was called down to the constructor. You'll see this migration, which were passing through as an argument, is then associated with this property. And then we have least off tables. Now the second private property, which is basic listing all of the tables that we want to have with our database. And now if we open model and queries and then whichever basically driver, you want to use your seed out, these reflect what we have in these directors now. If we scroll down, obviously here we associating their struck it within a construct, we associating what's being passed through as an argument and then up method. Basically, first of all, what we do is disable foreign key checks. Let's quickly check with this method. That's this method calls the DB method on the migration. If we opened this migration far, you'll see that the DB method simply returns the database instance. And if we go back to our database test, as you can see database instances of what we pass through as an argument to this migration call here. So the constructor associates that database instance with the database property off this migration class. So we return in the instance off this database here and we check in. If this db by six this database instance is off my SQL which would march the one from within the database driver and then this my SQL because only my sk on my SQL we can run this statement set old foreign key checks, foreign key checks and then said them to know bicycle. Don't check for foreign keys when we are running the following queries and then disable. Sorry, this is the disabled Foreign key checks obviously and then enable them back basically pulls them back into place. This is what what this gives us is basically when we create in databases which have any foreign key Frankie's relationships basically between the tables. Sometimes you might run into the bicycle problems when you run the bicycle queries in in the incorrect order. Basically, if one table is trying to set them the relationship while the table to which it creates the relationship does not exist yet. So that could cause basically some problems. That's why we disabling this foreign key checks first and then after we run this up, whether we wanted to run with this for each within this for each lobe, then we enable them back. And basically, what we doing here? We running through this through the records, basically interest off the tables, property, this array and recreated stables. If we go to this migration, create method, you can see it saves the file with the table names. Query Path Method basically prepares the type off the database, so check Walt database type. We are trying to run it on, and then I think it's going to be the sq light on my SQL and then fetches the correct fire masked with the extension dot PHP. As figure back to this, be up and off the creates a table and then down method does exactly same, but in the opposite way. So first of all, we reverse into the yard of the tables. So they're going to be rather than having them from authors to book locations is going to run from book locations to authors, and what is going to do is about to destroy them. Removed the table. So after their we've around this down it, none of the tables is going to exist, obviously, on the database. So now having this down method, it's probably a good idea to actually use it within our test. So we have set up, and now the next method we going to be working with is going to be called to you down protected function Tear Down, which is one of the methods on the PHP. If we go back. Test case PHP unit Framework Test case. And let's look for PHP asserting a PHP tear down. There we go. You can see tears down the fixture, for example, close a network connection. This method is called after a test is executed, so set up is run before test is executed. To your down is when the test has completed eso from within the tear down. What I want to do is first of all around the parent. Want your parent tear down if we have any. Obviously, as you saw previously, just a moment ago, there tear down within the speech. Be unit desk case was empty, but if we wanted to add one for all of the test, we could do it from within the test case, and then that would apply to all of our tests. So let's just say, basically create a cold to this method. And then what we going to do again? Another actually didn't typing this again. Let's just copy this entire line here. This migration manager would migration and rather than up, let's call down methods. So after each test, old database tables will be removed, and then before the next one, they will be recreated. And so So every time we're going to run the test from within this database test class here , we always going to start with a fresh migration with the fresh, empty tables. Basically, in this case, obviously we don't work with the data from the previous test. We always have a fresh fresh tables, and so Okay, let's run the test once again just to make sure everything works. Speech. You need hate return and all tests pass and we can now move to next video. 9. Database update and fetchObject method: next method that we need inside of our database subject is the method that updates the record simply update method. Again, let's start with the test. So within the database test or PHP file, we are going to create the new methods public function updates record. And the first thing we're going to do is to art new book records. So this art book. But this time we are going to specifically declare what we want the given field to have. And in this case, we're going to use I s A B N field, and we want it to be 123 And this is because we want to. After the update, we want to compare whether the update actually changed its value. So now we've added the book. Next thing I want to do is to update their records, So I'm going to create the update. Variable equals this DB instance, and on this instance, we're going to call Method update, which we obviously don't have yet and what I'm going to do, this method will take three arguments. 1st 1 is going to be a table on which we want to execute the update, which is going to be books, then their list of fields and values which we want to update. I s B and in our case. And we want to change it to 456 And the last one is the idea off the record that we are to update And the idea of this record is simply going to be this last insert i d and what I'm going to do now. And now where do we get this last instead? Idea If we look at this art book record, you'll see this method. You will see that here we are basically associating this property. Last insert body with the last instead i d from the pd object. So this is where we getting this from? A Okay, So added this. We've got this last instant ideas. 1/3 argument to this update method. The next thing we need to do is to check bicycle randy assertion this assert true and what we going to do is update and then the message will be the update statement failed a bicycle checks because I was the update. If it was successful, World which returned the equivalent off Boolean True, and obviously it's assert t d and off assert that we got search. There we go. And then once we once we know this has executed successfully returned show. Next thing I want to do is to fetch this new book. So it's going to be book equals this DB instance. And then we are going to create a method called Fetch Object and the statement that we're going to be passing as the first argument will be select all from, ah, books where I d equals in question work for the placeholder. And then the second argument of this method will be bicycle the parameters that we wants to bind to does. Placeholders, in this case is going to be this last insert idea again to refer it to the same record. So this will shoot Give us the record off this last other book. And then what we're going to check is this Assert equals 456 and book I s B and filled and a loss a argument will be the message. So I as b n waas not updated. Let's keep this way that go. Let's put on separate lines as well. So 1st 1 is what we expect. 2nd 1 is what we actually have. And the 3rd 1 is the message which is going to be shown should this assertion fail. Okay, so we've got all the methods. We've got the test ready. Obviously, we need to mark it as a test. So connotation with the talk test. And obviously, if we go to the terminal and Ron PHP unit, you'll see that we obviously get this call toe undefined method update on the sq light instance. And as obviously clear because we know exactly that we don't have this method yet. It will fail later on because of this method as well. So let's move to the database class and are this new update method. We're going to stop the public function update. And as you may remember, it takes three arguments or it actually can take even for But let's just go for them. So, tables Name was the 1st 1 table. Then the 2nd 1 will be off the array type, which is a data that we want to update basically containing array associative array, off keys representing field names, values representing values that we want to update on those fields and then we have the idea off the record and the last one we're going to pass in is going to be a field by default. It will be I d. But sometimes you may want to update records by a different field in Justin. I d. Okay, so we start with the SQL statement and this statement will start with update. And then we passed the table. I'm using again. Double it. So this back ticks and Kelly a bracket salt table set and then space semicolon. Now we're going to be looking for each data s key equals value. And when we going to do, he has ask you, Are we going to come coordinate it? Wit in between a double quotes, a key. So this is going to represent the field name equals question mark for the placeholder for their prepared statement. And then what we are going to do is create the values, actually areas well above here. So on the use equals array and empty rate to start with and we are going to answer this array the value which we want to bind later on to this place. All that Okay, Acid that's old is binding from within the four each. Then we have s Q l well, we continue with our statement space where and now we take field name Sofield equals question mark again. And for this question, more for this place holder We are going to aren't the values to the values, Ray. Basically, we're going to art d i d. So the value starting this third argument will be associated with 1/4 argument by default idea off the record. OK, so that's our SQL statement and values ready. So now all we need to do is return this execute method with the SQL, which we've just created here and values as the second argument. And that's all within the update method. Let's quickly generate dog blocks, he as well, and give us some description. It update. Ah, record. There we go. Okay, if we go back to the terminal around PHP unit again. Now we have this message, as we already discussed, fetch object which were having guilty it. So let's go back to their to the editor and rights after the update method, let's create this new one called fetch objects. It's again. It needs to be a public a method. So fetch object and this one will take Ah, four arguments. Let's put them on new lines. The 1st 1 will be the SQL statement We are going to be passing through. If I just crawled up a little bit and then we have para meters and now these might be in the ray or a single value. So this is why I'm not ah specifying Basically, I'm not hinting Type painting this with your A at the beginning because it may be a single Valium. By default, it will be no. Then we have class name which is basically their theon object that we want to return and then array. It's going to be for constructor argue men's by default is going to be an m a theory. We're going to start with a class name so class name equals It's either class name And if it was left no Then what we want to do is to use the standard class A STD class, which is the default class there will be used when you are actually trying to obtain any records from a data permit using PDO extension using the fetch class PDO constant. But we'll get to this in just a moment. Okay? So we've got a class name ready. Next thing we want to do is to create the statements or statement equals and we go for this query and we are going to pass the SQL statement, which is the first argument. And the 2nd 1 will be depart meters. And this is what I'm actually going to use typecasting to convert this second parliament his argument to a race. So if it's a single item, if it's a single bottle, let's say you pass just I'll say I know one as the second argument to march any off the placeholders within the SQL statement. Then this will be converted to the area using this typecasting here. So it's going to be converted this way by using this type custom I'm using here. Okay, So typecasting to array. And we need par meters. Okay, so this is our query now. Okay, Next thing what we going to do is to run this statement fetch mode, and this is the method we're going to create in just a second. And this one will take two arguments. 1st 1 will be our statement with the return statement from the Square E and Method and Den . After this one, we're going to pass array elf. First of all, we're going to use the fetch mold we want to use in. Our case is going to be PDO COLUMN Colon fetch class. There we go because we want to return the class rather than associative very or anything like else. And let's quickly have a look at this constant what it does. It tells us that it specifies that the fetch method shell returning new instance off the requested class, mapping the colons to named properties in the class. The magic underscore on the skull set method is called if the property doesn't exist in the request of class. So this is what this constant is going to cause. Basically, when we going to fetch records from a database is in this PDO extension, then the next one because that's not the only one that we need is going to be p. D o colon colon. Fetch props late and what this one does. Let's quickly have a look at the dog. Look for this especially constant, called the constructor before setting properties available since PHP five points. What does it mean when we using fetch class their way the PDO works. It would automatically associate properties without actually looking to the constructor without executing to construct the first. But this specific constant tells it, OK, before you start associating records at the fields with the properties off this object of this given class first, make sure that you run through the constructor, make sure that the constructor is executed first. It is as it would in a normal way when you actually instance hating the object. So that's basically what these two constants do. Okay, second item in this year, every will be the class name so close name. So it's going to be either the name that we passed through as 1/3 argument. Oh, standard class. Then we are going for the constructor arguments. These are going to be passed through the constructor if obviously, if we have any constructor within their given class at all. Okay, so this is fetch statement Note after this will be going to do is simply return statement and then fetch Now. We obviously don't have this statement fetch mode yet, So let's quickly create this method out methods statement fetch mold and this one will take these two arguments. I'm going to pull them on new lines and I'm going to type painted with the array by default . It's going to be an empty rate, and then statement will be taken as a reference. As you can see, I'm not associating whatever dis mattered to return so back to the statement. I'm just passing. This is an argument, and I want to do it this way because I don't really see that any need for actually re associating the statement again here. So we just pass it as a reference. And whatever happens with this, very able, basically, with this statement here is going to be reflected on the next line. So all these changes from within the statement fetch Mount will be reflected within this line as well. And the first thing I'm going to do here, actually, rather than calling disarray, which is rather ling, I'm going to call it fetch, mold it, which doesnt quiet, cover what it does because this array has a fetch. Multiyear has a class naming constructor arguments. I know it doesn't quite reflect what it is, but let's keepers fetch malt for now. OK, so we check in if is an empty and now this is the new property, which we haven't yet this fetch on the score mode. Then we're going to set this override this fetch moat argument with whatever associated with this fetch mold property. So let's quickly copy the name of it. I'm going to close the file browser, splits the screen and just go right to the top. And creating new protected property called Fetch Melt is going to be an empty rate by default. Let's quickly put dog blocks as well. It's in the ray and we cannot closet. Okay, so now we have this property available A. And the next thing I'm going to do is return. Ah ko user funk array and the first argument to dysfunction will be Thea object, something called Herbal basically, and I want to call the method set fetch mold on the statements on passing the statement as the first argument and then the name of the method as a string set fetch moat. So on this statement object I want to called set fetch moat with fetch moat arguments by six each of these arguments will be converted to sit there. Each of these items off this furch melt array will be converted to the argument off this method and passed through to this method as arguments. Basically, this coal use it fun. Correct. That's exactly how it works. You can obviously look it up on PHP dot net to read a little bit more about this function itself. Okay, so that's what we're going to do. So basically going to coal set fetch moat on this PDO statement. Object A. And I think this method is now complete. Its let's just quickly are the dog blocks again on Let's give some description. Uh, state set statement. Fitch mold. Um, yeah, I think that's fine. And down this same for the fetch object. And what this one does it fetch? Object. That's what does Basically Okay now another method a we don't have yet is this Query one. And while this query method basically ISS, it's it's going to delegate call to the execute method, which we already have, but it will by default, said the fourth argument, two false meaning that we wants to return the statement rather than true or false. By ending their the coal. In other words, because we still want the statement. Want to Cheney later on one to pass it later on as an argument. And if I just quickly split the screen here and look for this execute method, you will quickly see if I just go this way, you'll see this fourth argument he has set to true, and by default it will return the result. It won't return the statements. The PDO statement it will return results with it's been successful or not, basically, whatever the statement execute has returned. But this query will simply set it to false, and in that case, we going to get the statement box in. Obviously, we can now change later. So let's close this split screen here and let's just create this method I'm going to create right after this statement Fetch moat and it's going to be a private. Actually, let's set its public because we can set it. We can use it from outside of this class as well, and the method coal is sa admitted, name is query, and it will sake just put them all new lines. Three. Argument. SQL is going to be the first ones with statement than every perimeters, which we are going to bind to those ah question marks biting the placeholders off our ah statement. And then the last one will be driver options, driver options and empty areas. Well, okay, so from within this query one what? We are going to do it Simply delegate the coal. We go into delegated culture, the execute methods. So return this execute and we parcel this arguments as we got them through. And let's just put them on new lines as well. So we can clearly see what's happening here. Then party meters goes a 2nd 1 Driver options s the 3rd 1 There we go. And the last option, I'm going to set it to false. So we biting the squaring well will return the PDO statement. So that's all this query method Wilder that's quickly out the dog blocks we go. And as you can see, it either returns bullion, our PDO statement. But that's not quite sure because this execute. When we said that last four arguments to false, it will definitely return statements that we can remove this bullion from here. Okay. And what we going to put here. Execute query, SQL query And I was just That's just keep Is this execute square? Yeah, all fine. Let's now go back to the terminal and round PHP unit And there we go. Full test, five assertions, all of which passed. So if we go back to our test date of the best test, if we try and change it toe, say assert false as human dot This statement fell. This update statement felt it's obviously going to fell because it returns true and we assuming that it returns, falls. If I clear the screen, reverse it back to what it waas True, that's fine. And then, if we change the updates value, let's say for 58 that should fellas. Well, because we comparing against 456 And as you can see that size being was not updated, Felt are stating that 458 march is expected expected for 56 which we are checking for here . So if we put it back to six, that's going to pass for just around PHP unit again and all our tests are passing and we are ready to move to next video 10. Fetch object tests: in a previous video have created this updates record test and then we've created the update and fetch object methods on the database class. Now, one thing we haven't done. Actually, we haven't Britain any proper tests for this fetch object method. So this is what we're going to focus on in these video after our updates. Records test. Let's create a new one. Cold fetch Object returns S T D class instance for the 1st 1 the default one, As you may remember, if we just go back to the database and if we go back to our way, fetch object. If we didn't pass the third argument, then it's going to return the default STD Standard Class Basically instance. So that's what we're going to be destined for. So first of all, we go into art book this art book and let's pass some values say title equals more could equal book off Jungle, for instance. So now we've got a book record. Next thing we're going to do is to fetch this record. So book equals this DB instance of our database object, fetch, object, and we passed there the SQL here, which I'm going to remove this put on new lines. Our SQL will be select all from books where I d equals and a placeholder question mark. And then for this question mark to bind to it, we are going to use this last insert idea. Whatever this insert idea from within, this art book method has returned. This is the record we looking for. So now we're going to do. Is this assert instance off? And we are assuming that this specific method, without the third argument, this fetch object should return STD class and then class because that's what we want to return. We want to basically check for the name of this class to get using any any name spaces if there are any, and then book A which has been returned from this fetch object. So the instance and then the message I'm going to put again on new lines here semicolon d and obviously, And then if we scroll up the message will say something like, Did not return a STD