In this fourth part of the mini series of tutorials regarding object-oriented programming in Php we will see an example that will summarize the topics covered in the 3 previous articles.
Below we link to the previous tutorials:
The topic of the example will be centered on CRUD operations. CRUD is the acronym for Create, Read, Update and Delete, they are simply the four operations that are performed on data structures such as CSV, Json files or on databases. CRUD operations represent the creation of data, its reading, its modification and its deletion. In our example we will use a Json structure since we didn’t talk about databases in the previous episodes.
The data structure
To start we need to get some fake data to manipulate, and on the web there are many sites that make invented structures available ready to be used, one of these sites is https://www.mockaroo.com. Here we can find a lot of material that can do for us.
In Figure 1 we can see the home page of the site, where it presents us with an initial structure that we can modify. Let’s now see some points to customize the data we need.
- By dragging the six points we can change the order of the fields. In the box next to the six points we can change the name of the data.
- By pressing the drop down at point n 2 we can change the data type.
- By pressing x we delete the fields.
- In the Rows box we can change the number of rows.
- In the format box we can change the format of the generated file.
We make some changes to the scheme by changing the name of the last field from IP_ADDRESS to image, we change the Dummy image URL, we change the Rows field from 1000 to 10, and finally we change the Format field from CSV to Json. Now we are ready to download the data by pressing the green button at the bottom GENERATE DATA (Figure 2).
Clicking on the button will start the download of a json file called MOCK_DATA.json, with the data invented and structured as we asked.
The structure of the project
Now we will create the project with the various files and subfolders that we will need to bring our example to life. First we create the main folder, we will put it in any point on our PC which can be for example on the desktop and which we could call for example user_management. Inside it we create six other folders which we will call public, class, function, css, js and json respectively. Maybe in this case we won’t use them all, but in the meantime we’ll do them anyway. in the json folder we will copy the previously downloaded file called MOCK_DATA.json into it. Let’s now open the public folder and create a file inside it that we will call index.php. In the css folder we will create a file called style.css which can always be useful.
For the moment we can suspend the creation of the structure and move forward with developing some code. But first, since the eye also wants its part, let’s import a framework for the creation of web graphic interfaces, just to embellish our pages a little, the first that comes to mind is Bootstrap, which is It is an excellent development tool among the most used, if not perhaps the most used in the world, rich in features and tools to generate any type of layout you want to create. But if we think about it carefully, we don’t want to talk about something that everyone is already talking about, so we’ll set aside the idea of Bootstrap and instead use the small but versatile Skeleton css, made up of only two css files and removing the comments of not even 200 lines of code in total. We can download it here.
In Figure 3 we can see the main (and only) page of the Skeleton CSS site which, in addition to the presentation, also acts as a manual. By clicking the blue download button we can download the ‘miniframework’ from which we will only take two css files, called normalize.css and skeleton.css, which we will copy into our project, in the css folder. Now let’s open the index.php file and insert the following code into it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>User Management</title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="../css/normalize.css"> <link rel="stylesheet" href="../css/skeleton.css"> <link rel="stylesheet" href="../css/style.css"> <!-- <link rel="icon" type="image/png" href="images/favicon.png"> --> </head> <body> <div class="container"> <div class="row"> <div class="one-half column" style="margin-top: 25%"> <h1>User Management</h1> </div> </div> </div> </body> </html>
Let’s begin
Now we can dedicate ourselves to creating the little program. Let’s go to the class folder and create two files which we will call one User.php and the other ManageUsers.php, in these files we will build classes inside them. Let’s start immediately with User.php. In this file we will create a class called User which will serve to group all the data of each individual user into an object in the form of properties which we will manage with the appropriate getter and setter methods. Now let’s look at the MOCK_DATA.json file (Figure 4.).
Let’s now take the keys of the values of an object which are id, first_name, last_name, email, gender and image and use them as properties in the User class that we will create in the User.php file
<?php class User{ /* * I define the properties */ private $id; private $firstName; private $lastName; private $email; private $gender; private $image; /* * I create the constructor */ public function __construct($id, $firstName, $lastName, $email, $gender, $image) { $this->id = $id; $this->firstName = $firstName; $this->lastName = $lastName; $this->email = $email; $this->gender = $gender; $this->image = $image; } /* * I create getter methods */ public function getId() { return $this->id; } public function getFirstName() { return $this->firstName; } public function getLastName() { return $this->lastName; } public function getEmail() { return $this->email; } public function getGender() { return $this->gender; } public function getImage() { return $this->image; } /* * I create the setter methods */ public function setId($value) { $this->id = $value; } public function setFirstName($value) { $this->firstName = $value; } public function setLastName($value) { $this->lastName = $value; } public function setEmail($value) { $this->email = $value; } public function setGender($value) { $this->gender = $value; } public function setImage($value) { $this->image = $value; } }
Here we have created our beautiful User class, where we have defined properties with the scope of visibility set to private, so as to have greater control over the variables and consequently a lower probability of error. We then created the constructor and set the getter and setter methods. Now let’s open the currently empty ManageUsers.php file and create the ManageUsers class inside it. In this class we will put all the methods that will be used to manage the program.
<?php require_once "User.php"; class ManageUsers{ private $user; private $dataUsersToArray; /* * Path of the json file * */ private function pathFile():string { return $path = "../json/MOCK_DATA.json"; } /* * I open the json file * I convert the json to an array */ public function listOfUsers() { // I check if the file exists if(!file_exists($this->pathFile())){ return []; } $dataUsers = file_get_contents($this->pathFile(), true); $dataUsersToArray = json_decode($dataUsers, true); return $dataUsersToArray; } /* * I create an object for each user with all its properties * I put all the objects in an array */ public function createUser() { // Create an array containing all the objects, one for each user $user = []; foreach ($this->listOfUsers() as $key => $value) { $user[] = new User($this->listOfUsers()[$key]['id'], $this->listOfUsers()[$key]['first_name'], $this->listOfUsers()[$key]['last_name'], $this->listOfUsers()[$key]['email'], $this->listOfUsers()[$key]['gender'], $this->listOfUsers()[$key]['image'] ); } return $user; } }
Now let’s edit the index.php file as follows.
<?php require_once "../class/ManageUsers.php"; $manageUsers = new ManageUsers(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>User Management</title> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="../css/normalize.css"> <link rel="stylesheet" href="../css/skeleton.css"> <link rel="stylesheet" href="../css/style.css"> <!-- <link rel="icon" type="image/png" href="images/favicon.png"> --> </head> <body> <div class="container"> <div class="row"> <div class="one-half column" style="margin-top: 25%"> <h1>User Management</h1> <?php for ($i = 0; $i createUser()); $i++) { echo "First name: <b>" . $manageUsers->createUser()[$i]->getFirstName() . "</b><br>"; echo "Last name: <b>" . $manageUsers->createUser()[$i]->getLastName() . "</b>><br>"; echo "<hr>"; } ?> </div> </div> </div> </body> </html>
If we now test the program we see the result as follows in Figure 5.
In this example we have seen how it shows the users, in the next articles we will also see how to carry out the modification, deletion and creation operations.
SviluppoMania
Stay Tuned