2022/2/24 00:41 Module 5
This is a single, concatenated file, suitable for printing or saving as a PDF for offline viewing. Please note that some animations or images may not work.
Module 5 Study Guide and Deliverables
Readings: Assignments: Live Classrooms:
Copyright By PowCoder代写 加微信 powcoder
Murach’s PHP and MySQL: Chapters 5, 14, & 19 Assignment 5 Due: Thursday, February 17 at 6:00 AM ET
Thursday, February 10, 6:00–8:00 PM ET Facilitator live office: TBD
Object Oriented Programming Paradigm
Learning Objectives
By reading the lectures and textbook, participating in the discussions, and completing the assignments, you will be able to do the following:
Describe the object oriented programming paradigm.
Define classes and instantiate objects with PHP.
Use advanced object oriented programming concepts.
Implement programs using the MVC design pattern.
Identify some of the more popular PHP MVC frameworks available today.
Introduction
In this lecture, you’ll learn about the object-oriented approach to building web applications. You’ll start with the very basics and then move on to some more advanced features of this paradigm. We will also discuss the Model View Controller design/architectural pattern and implement a small stock quoting application using MVC. Finally, we will briefly cover some of the more popular MVC frameworks that are available for PHP programmers.
Object Oriented Programming Paradigm
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 1/47
2022/2/24 00:41 Module 5
A paradigm a way of approaching or thinking about things, you could also call it a thought process. One way to explain object oriented programming (OOP) is to contrast it against something we already know. In the previous module, you learned how to create PHP programs in a “procedural” manner. The variables and functions were normally separated from each other. We took a variable, gave it to a function as input, and the function gave us back some type of output after it was done processing. It looked something like this:
With OOP, we take our variables and functions and wrap them together into a single object. We then refer to the variables as properties and/or attributes and our functions as methods, and sometimes even behaviors.
Note: You’ll also hear the terms member variables and member functions. These terms refer to properties and methods, respectfully.
Here is a high level look:
Let’s take a dog and use it as an example for this explanation. Our dog is going to be an object. We know that objects have attributes and behaviors. What attributes could we derive from our dog? How about:
Weight Friendliness Name
Those are just a few, we could certainly think of more if needed, but I hope you are getting the general idea here. Now let’s look at our dog’s behaviors (methods):
Eat Sleep Run
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 2/47
2022/2/24 00:41 Module 5
Jump Bark Lick Fetch
Those are all things that dogs can do.
So an object contains both properties and behaviors. This is the important distinction between OOP and procedural programming.
Benefits of Object Oriented Programming
It is important to note that you don’t necessarily “need” to use OOP. It does have it’s advantages, especially when our programs become larger. Switching to OOP can bring a sense of simplicity to complex programs. OOP gives us the ability to create modular, manageable, and organized code. It also gives us the structure needed to help with scalability.
Probably the most noticeable benefits come with abstraction and encapsulation. Encapsulation is very important as it allows us to define our data and program structures together in an object and hide the implementation from whoever or whatever needs to use our objects. Instead, we provide an interface that exposes the functionality while restricting direct access. An analogy would be that you shouldn’t need to directly interact with an engine in order to operate a vehicle. You just need to be able to control the speed and direction of the vehicle and you can do that with a gas pedal, brakes, and a steering wheel. In this case, our engine is the implementation and our gas pedal, brakes, and steering wheel are the interfaces provided to us to operate the vehicle.
We also gain some very powerful concepts with inheritance and polymorphism. We’ll see how all of this works as we start building our programs with an OOP approach.
Before we start using objects, we need to talk about classes. A class is simply a blueprint for an object. When we create our objects, we use a class as the template that specifies how the object is built. A class is not an object, it is just used to describe one. An object cannot be created without a class.
The class defines the attributes and behaviors that all objects derived from the class will have. Classes must define the basic building blocks of the objects.
Let’s look at a class definition in PHP:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 3/47
2022/2/24 00:41 Module 5
The file was saved as Dog.php.
You can see that we use a keyword class and then choose a name for the class, which in this case, we selected a name of Dog. We have an opening and closing set of curly braces in which we put all of the member code of the class within.
We create our member variables, or properties, prefixing it with the var keyword. The variables are $name, $breed, and $friendly.
Note: We will eventually discuss visibility or access modifiers. The var keyword was originally depreciated in PHP 5, but has made a comeback as of PHP 5.3. In this case, var is an alias for the public access modifier.
We then declare a few methods. The types of functions we have created here are known as setters and getters. Setters allow us to set the value of properties for an object and getters allow us to get the value of the properties from an object. We’ve created a setter and getter method for each property within the class. Just as mentioned above, we’ll cover access modifiers later and for now, we will just use the function keyword for declaring our methods.
You may have noticed some new syntax inside of our methods. Let’s focus on these a bit:
$this : A special variable that is always available to an object within it’s scope. It refers to the current object.
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 4/47
2022/2/24 00:41 Module 5
-> : The object operator. It is simply a hyphen (or dash) and a greater than sign combined together to form an arrow. It is placed between the object and the property or method that you want to access.
If we were to view this file in our web browser, we would get a blank page. All we have done is create the blueprint for an object, we haven’t actually created one yet. We’ll do that in the next section.
Some things to keep in mind about classes in PHP:
Class name must start with a letter or underscore.
The remaining characters must be letters, numbers, or underscores.
Best practice encourages you to name your classes using UpperCamel notation, being sure to capitalize the first letter of your class name.
Properties should be written in regular camel case or have words separated with underscores.
Class Constants
We can also include constants in our class declarations. You already know that a constant is like a variable and can hold any value, but it can’t be changed after the program starts to run. Another way to say that is that constants are immutable. In our class declarations, constant declarations are preceded by the const keyword.
We have already learned a little bit about objects when we covered classes in the previous section. One thing to understand about an object is that it is a data structure that is more complex than the primitive data types we learned about in Module 1. As you’ve learned, an object can contain multiple data types.
Once you have your class created, it is fairly simple to create objects belonging to that class. In order to create a new instance of an object, declare a regular variable and assign it to: new ClassName;
It will look something like this:
$dog1 = new Dog;
From there, we can access the properties and methods of the object as needed. Let’s create some Dog objects based off of our Dog class:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 5/47
2022/2/24 00:41 Module 5
This is what we will see in our browser window:
You can see that we’ve created a new file and saved it as objects.php. In this file, we start off with: require(‘Dog.php);
This line tells PHP that it needs to copy the contents of the specified file and include it in the current file. You can also use include(), include_once(), or require_once(). require and include do the same thing, but they react differently if there is an error. require() halts execution if an error is encountered while include() simply provides a warning message. The include_once and require_once variations do the same thing as their simpler counter parts with the additional feature of having PHP check to see if the file has already been included, and if so, it will not include (or require) it again.
After the require statement, you can see that we instantiate three different dog objects. We then set the names, breed, and friendly properties using the object’s setter methods.
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 6/47
2022/2/24 00:41 Module 5
Finally, we string together an echo statement that accesses the properties of the objects using the getter methods. We’ve also introduced some new code here, the ternary operator, which isn’t for exclusive use with objects. We can use this anywhere we would normally use an if else statement, it’s just a shorter way to express the same thing.
Constructors
When we covered classes and objects in the previous section, we intentionally did not use a constructor. A constructor is a special method that is called when we instantiate an object. Technically, this special method is known as a magic method in PHP and we denote this with two underscores at the beginning of its name.
The constructor is automatically called when we instantiate an object. It is used to set up or configure the object.
Let’s go ahead and revise the previous class and object files in order to show how constructors are implemented and used.
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 7/47
2022/2/24 00:41 Module 5
In the example above, we saved the file as BetterDog.php and have also changed our class line signature to reflect BetterDog as the name of the class.
Let’s go ahead and look at our new objects file that utilizes the constructor we created in our BetterDog class. We’ve changed our objects file name to objects2.php
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 8/47
2022/2/24 00:41 Module 5
When we load this version in our browser, this is what we will see:
You should be able to determine that this is the same result as our previous example. We just had to write a lot less code in the latter because our constructor allows us to give it a few parameters and it sets up our object for us.
Destructors
__destruct() is ran when an object needs to be destroyed. PHP calls a destructor as soon as all references to an object are freed up or when the script terminates. You don’t need to call this explicitly and you really shouldn’t unless you have a specific need to do so.
Inheritance
Another powerful feature of object oriented programming is the ability to reuse code. OOP allows us to define relationships between classes. We can organize our classes and take into consideration the commonalities between similar classes. This is the core of what “Inheritance” is all about.
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 9/47
2022/2/24 00:41 Module 5
Put another way, with inheritance, a child class can inherit the properties and methods of a parent class. Because this is available to us, we should always be “thinking more abstractly” when we start designing our programs with OOP.
Let’s return back to our example involving dogs. We were very specific when we created the dog class, so much so that it really isn’t feasible to create child classes from the Dog class. We could create a subclass (child) named small dog to try and show a distinction between large dogs and small dogs, but that really doesn’t give us the best example of inheritance. What would make sense is to find a way to create a parent class of Dog that we could then create other child classes from. What do dog’s and cat’s have in common? They are both mammals, so let’s create a Mammal class and we can then recreate our dog class as a child of Mammal and also create a Cat child class as well.
Let’s start off with creating the Mammal class:
It is probably worth noting that even though we can, we probably won’t be creating any Mammal objects. Instead, we will be creating Dog and Cat objects. So let’s go ahead and create these two child classes.
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 10/47
2022/2/24 00:41 Module 5
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 11/47
2022/2/24 00:41 Module 5
You can see in both examples that we require the Mammal.php file. We then use the extends keyword after the class name and then indicate the parent class name. Everything else within these files should be familiar to you except for this line of code within the constructor:
parent::__construct($pName, $pFriendly);
That line calls the parent constructor and passes along the two parameters it needs to setup the object. The double colon is known as the Scope Resolution Operator. This operator provides access to static, constant, and overridden properties or methods of a class.
Now let’s look at the files where we declare our Cat and Dog objects: cat_objects.php
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 12/47
2022/2/24 00:41 Module 5
dog_objects.php
And here are their respective screen shots when viewed in the browser:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 13/47
2022/2/24 00:41 Module 5
You can see that we did something different when we created our Dog object compared to when we created our Cat object. For the Dog object, we used the setName() method on it to change the name to a different value from what we used to create the object. There is no setName() method in the Dog class, however there is one in the Mammal class. Since Dog is a subclass of Mammal, it can call the methods that are contained within the Mammal class.
Overriding Methods
You can override method declarations in a parent class by declaring a method with the same name in the child class. In our Dog example, let’s say that we originally named our dog when we instantiated the object, but we now want to pass the string “later” to setName() as an indication that we have changed our mind and haven’t come up with a name yet for our Dog.
We can accomplish that like this:
This is what we will see in our browser:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 14/47
2022/2/24 00:41 Module 5
This is the behavior we should expect from setName(). That method belongs to the parent class of Dog and it simply assigns what we pass in as a parameter to the instance variable $name for our Dog object. Maybe that is what we want for most Mammals, including Cats, but we want it to work differently for Dog objects. We can do that by overriding the setName() method inside of the Dog class like this:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 15/47
2022/2/24 00:41 Module 5
Now if we run the code listed in the screen shot above, we will see this in the browser:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 16/47
2022/2/24 00:41 Module 5
Yes, there are other ways that we could have accomplished this, like assigning NULL to the $name instance variable. But this example is intended to show you how we can use the same name of a function in a child class that has already been declared in the parent class in order to override the behavior for the method when used for a child class object.
Access Modifiers
We have been using the var keyword to declare our member variables up to this point. As mentioned earlier, the var keyword is simply an alias for public in PHP 5.3+.
Public is one type of access modifier (also called a visibility modifier), but there are two others as well that we will explain here:
Properties and methods can be accessed outside of the class in which it is declared, from within the class in which it is declared, and from within another class that implements the class in which it is declared.
Properties and methods are limited to the class in which it is declared. They can not be accessed from outside of the class or from classes that inherit the class in which it is declared. (It is best to use this sparingly)
Properties and methods are accessible in the class in which it is declared and in classes that extend that class. They are not available anywhere else.
What the access modifiers really end up doing is defining the scope of the properties and methods of the object or class.
We will now use the keyword public instead of var moving forward when we declare properties and methods.
In some cases, you will want to make your properties protected and use a public method to access the properties instead of providing direct access to the properties by leaving them public.
Let’s go into our Mammal.php file and make a couple of changes:
Set $name and $friendly to “protected” Add a private function named sleeping()
It will look like this:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 17/47
2022/2/24 00:41 Module 5
We will then create a Dog object, inspect it’s properties with var_dump() and then try to use the sleeping() method that we declared in our Mammal.php file.
Here is what we will see when we view it in the browser:
https://onlinecampus.bu.edu/bbcswebdav/pid-9762729-dt-content-rid-60368381_1/courses/22sprgmetcs602_o1/course/module5/allpages.htm 18/47
2022/2/24 00:41 Module 5
You can see that it is telling us that name and friendly are protected now and that we have an error when trying to call the private method Mammal::sleeping() from within the access_modifiers.php file because we are trying to call this outside of the Mammal class.
Abstract and Final
There are two modifiers that are similar to access modifiers that we have not discussed yet: Final and Abstract. Final
This keyword can be used to declare that a function or class cannot be overridden by a subclass. Abstract
This keyword is used when you want to p
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com