1. The syntax is based on PHP, and different programming languages have different approaches, but they are generally the same.
  2. The idea of object orientation is to understand and use it.
  3. The interfaces mentioned in this article are the interfaces of the programming language syntax, not the apis called by the front end.

Why are there so many concepts? Know why.

Software, is to solve the problem of human development, convenient tools for human, if a computer, or a software can only count, then how to meet exchange rate conversion? Is it possible to say that a computer can’t do something without having too many inherent functions? Now software can help people shop, date, entertain. So complicated function, if the software thought did not develop more advanced thoughts, it is not for human services, more so for maintainability and has stronger function, must be made in computer software programming itself on some of the more advanced concepts, more complex than is used to implement the addition, subtraction, multiplication, and division of function, diversification rules has become a set of practical and efficient specification, So that’s the various computer terms we’ll see below.

object-oriented

oriented

“Orientation” here can be understood as the way to program.

object

Object is a kind of programming idea centered on things, everything is an object, events are triggered by entities, objects are real, objects can also be understood as the data structure and the method of processing them, composed of objects. Three goals of software engineering are achieved: reusability and extensibility. Reusability: Methods in a class can be used more than once. Flexibility: can be manifested as polymorphic, can be repeatedly transferred and other characteristics, high degree of freedom, all roads lead to Rome. Extensibility: Polymorphic, inheritance have this feature, can be easy to diversify the extension, pull out, reduce coupling.

class

It can be understood as an abstract concept of objects, separating out the same characteristics and categorizing them. Objects with the same behavior can be classified as classes. One person is an object, but multiple people can be classified as a human. Human refers to a virtual entity concept rather than a certain one. Why is there this class? Because people have hands, they use fire, they are civilized, they are good learners, and so on. If you want to talk about someone in terms of human beings, you have to give an example, you have to instantiate.

Member attribute

Attributes can understand data, which is the carrier of information and representation. According to man, for example, man has nose and eyes, which is the attribute of man. It can be described as having.

Members of the method

Methods can be understood as functions. The method is to control the steward of the data. According to the example of man, man can talk, can eat, this is the way of man. It can be described as doing.

interface

It can be understood that a class needs to specify what it needs to do, but doesn’t need to do it. It acts as a canonical example, a standard that other classes need to implement. For example, define the size, size and data line connection method of USB interface, which can be analogous to an interface specification, universal USB interface all over the world, whether it is U disk, charger line, mouse, keyboard. All of these instances can make things according to this constraint specification. The use of interfaces needs to be described in two words: implementation.

Class has three characteristics

Encapsulation: Encapsulates the internal methods or data of a class to ensure security by allowing access to only accessible resources. Personification, where the name is public and the bank password is personal, is available in PHP as public protected private.

Inheritance: Inheritance generalizes a class, and a son inherits from a parent to obtain non-private properties or methods from the parent or beyond, using the extends keyword.

Polymorphism: Dynamic dispatch based on object type can be realized, different people do the same thing, get different results. Blind date this matter: the girl encounter rascal will say roll, encounter handsome boy will say yao yao da.

7 principles of programming in object-oriented scenarios. Purpose: Interface oriented programming, target oriented programming. Simplify code and reduce coupling. Flexible separation, reduce the impact. Separate the same code for easy reuse and maintenance.

Rule of uniformity: a class does one thing, and responsibilities are completely encapsulated in a class. Less clutter, more reuse, and less coupling can reduce maintenance in the later stages of software development.

Open closed principle: Closed for modification, open for extension. The code needs to be changed due to requirements change, operating environment upgrade and other reasons. If there is no bug, it is not recommended to change the original code, and can be expanded on the original basis. It not only increases the scalability, but also ensures that the original logic does not cause problems. So much for “ancestral code, don’t move.”

Richter’s Principle of substitution: In layman’s terms, everything that can be used by the father can be used by the son. Base class objects that can be used in software, then subclass objects can be used anywhere without being affected. A subclass can replace a parent class wherever it appears in the program, with logic unchanged and correct, implying that overriding the parent class is not recommended. Because of this standard, can prevent the parent once modified, will be affected by the failure of the child. This principle implements the form of the open close principle, where subclasses are equivalent to extensions. Essentially, this principle tells us what to pay attention to and what principles to follow in inheritance. But inheritance is to increase the coupling relationship between parent and child classes, in order to solve the dependency, can be appropriate through aggregation, combination, dependency, etc.

Dependency inversion principle: Programming to interfaces. Placing common reusable methods into abstract classes, abstract-thinking programming, or interfaces in a way that is abstractly coupled is the key principle to reduce coupling. Higher-level modules (for example, higher-level modules are the code at the bottom of the framework and, in PHP’s case, much of the code at the bottom of the framework is abstract classes or interfaces) do not depend on the underlying modules; they depend on abstractions. Abstract should not depend on details, details should depend on abstraction, that is, to achieve the separation of details and non-details, relative to the variability of details, abstract things are more stable. An architecture based on abstraction is much more stable than one based on detail. For example, the general implementation of functionality can be implemented using abstract classes, but the details can be implemented using concrete classes. The abstraction here is used to customize the specification and overall architecture. Here’s an example:

// This code is suitable for sending emails, but it is troublesome to add the function of sending wechat messages. Don't say "Email $Email" is removed, if a lot of the business logic in the project is already written in this way, remove "Email $Email" may cause problems.

      
class Email {
   public function send() {
        return 'Send an email'; }}class WeChat {
	public function send() {
        return 'Send wechat messages'; }}class Person {
	public function receive(Email $email) {
		return $email->send(); }}$person = new Person();
echo $person->receive(new Email());
Copy the code

Look at the result of optimization. The so-called abstraction is to send information, and the detail is the way and content of sending information. Abstraction and detail are separated, reducing coupling.


      

// The interface defines the general method, the general direction
interface SendMsg {
	public function send();
}

// Concrete classes to implement the details
class Email implements SendMsg {
   public function send() {
        return 'Send an email'; }}// Concrete classes to implement the details
class WeChat implements SendMsg {
	public function send() {
        return 'Send wechat messages'; }}// Reduce the coupling here
class Person {
	public function receive(SendMsg $send_msg) {
		return $send_msg->send(); }}$person = new Person();
// Flexible call
echo $person->receive(new Email());
echo $person->receive(new WeChat());
Copy the code

Interface isolation principle: In order to reduce coupling and reduce the bloated code segments in interface classes, the dependence of one class on another class should be established on the smallest interface, which is to provide what is needed and not to provide what is not needed. For example, the interface class Test has five methods func1, func2, func3, func4 and func5. A class relies on the interface func1, func2 and func3 of Test, and B class relies on the interface func1, func2 and func4 of Test. Such interface func5 is not used, the interface should be split, divided into class A and class B dependent interface is only enough interface, and increase security, here the disassembly, is to have the role of isolation of unnecessary code.


      
// The interface defines five methods
interface TestInterface {
   public function func1();
   public function func2();
   public function func3();
   public function func4();
   public function func5();
}

Class A relies on the three methods of the interface, func4 and func5, but not on them
class A implements TestInterface {
   public function func1() { return 'Implements the func1 method of the TestInterface interface'; }public function func2() { return 'Implements the func2 method of the TestInterface interface'; }public function func3() { return 'Implements the func3 method of the TestInterface interface'; }public function func4() { return 'These two methods are not available, but need to be implemented due to PHP syntax problems'; }public function func5() { return 'These two methods are not available, but need to be implemented due to PHP syntax problems';}
}


Class A relies on the 124 methods of the interface, but func3 and func5 are not used
class B implements TestInterface {
   public function func1() { return 'Implements the func1 method of the TestInterface interface'; }public function func2() { return 'Implements the func2 method of the TestInterface interface'; }public function func3() { return 'These two methods are not available, but need to be implemented due to PHP syntax problems'; }public function func4() { return 'Implement the func4 method of the TestInterface interface'; }public function func5() { return 'These two methods are not available, but need to be implemented due to PHP syntax problems';}
}
Copy the code

Look at non-bloated code:


      
interface TestInterface_A {
	public function func1();
	public function func2();
	public function func3();
}

interface TestInterface_B {
    public function func1();
    public function func2();
    public function func4();
}

Class A implements the 123 methods of the interface without relying on additional methods
class A implements TestInterface_A {
	public function func1() { return 'Implements the func1 method of the TestInterface interface'; }public function func2() { return 'Implements the func2 method of the TestInterface interface'; }public function func3() { return 'Implements the func3 method of the TestInterface interface';}
}


Class A implements the 124 methods in the interface without relying on additional methods
class B implements TestInterface_B {
    public function func1() { return 'Implements the func1 method of the TestInterface interface'; }public function func2() { return 'Implements the func2 method of the TestInterface interface'; }public function func4() { return 'Implement the func4 method of the TestInterface interface';}
}
Copy the code

Principle of composite reuse: More combination (HAS-A) and less inheritance (IS-A) can reduce the degree of coupling between classes. Encounter additional functionality that needs to be extended through association rather than inheritance. Because of the use of inheritance, late changes to parent code can cause errors by linking parent code to child code. Inheritance multiplexing is also called white box multiplexing, and combination polymerization is called black box multiplexing.

A software entity should interact with other entities as little as possible, which limits the width and depth of communication in programming. No matter how complex the dependent class is, it should try to encapsulate the logic inside the class as much as possible. In addition to providing public methods externally, it should not disclose any irrelevant information externally. Communicate only with friends, which are usually the current class, the current object, member properties, member method parameters, and member method return values. The rest are strangers and cannot be called directly. The law can be divided into the narrow law and the broad law. In A narrow sense, class A is associated with class B, and class B is associated with class C, so class A and C cannot be directly accessed and need to go through B. The advantage is that the coupling is reduced, while the disadvantage is that it requires A lot of local design, so that class A can access class C, resulting in reduced efficiency of inter-module use. In a broad sense, we can create loosely coupled classes as far as possible to control information overload. The lower the degree of coupling between classes is, the more beneficial it is to reuse, but higher abstraction separation is needed.

And thus appeared 23 design patterns, design patterns used to solve classical problems under the classic scene and out of the general practical specifications. But some of the 23 do not work in PHP, and when they are mandatory, they lose the benefits of weakly typed languages.

extension

Process oriented

Process oriented is based on the event as the center, analyze the steps to solve the problem, divide the code into a number of processes/functions, step by step implementation, where the function or process is the smallest module encapsulation unit, and then call these functions, can be called methods. In layman’s terms, encapsulation means wrapping a bunch of code around each other. Object oriented is also based on the idea of process oriented, object oriented implementation, there must be a corresponding process, so there are many similarities.

The difference between a procedure and a function

Procedure: No return value. Function: returns a value.

There are six relationships between classes: inheritance, dependency, association, aggregation, composition, generalization, and implementation

Inheritance: the son inherits the father, and a subclass can use any non-private member methods or member attributes of the parent class, and can be extended at will, and can relax access to resources through subclass overrides, and can override non-private methods or member attributes of the parent class. Easy to understand, not much explanation.

Dependency: If there are two classes, A and B, and one of the member methods of class B has A parameter of class A, then class B depends on class A.


      
class A {
    public function one() {
        return 'one'; }}class B {
    public function two(A $a) {
        return $a->one(); }}$b_obj = new B();
echo $b_obj->two(new A());
Copy the code

Associated: strong dependency, when dependencies has become a class member, at this time will be loaded into memory, rather than a parameter when (if it is pure rely on, so if you do not depend on the method call, what will happen), has a one-to-many association, many-to-many, there are one-way two-way, such as unidirectional one-to-many.


      
class A {
    public function one() {
        return 'one'; }}class B {
    public $obj_a;
    public function two() {
        $this->obj_a = new A();
        return $this->obj_a->one(); }}$b_obj = new B();
print_r($b_obj->two());
Copy the code

Aggregation: The relation of A and B is the relation of whole and part (HAS-A), which can be separated. DemoDateTime contains DemoDate and DemoTime. That is, DemoDateTime aggregates DemoDate and DemoTime.


      
class DemoDate {
    public function getDate() {
        return date("Y/m/d"); }}class DemoTime {
    public function getTime() {
        return date("H:i:s"); }}class DemoDateTime {
    public function getDateTime() {
        $date_obj = new DemoDate();
        $time_obj = new DemoTime();
        $datetime = $date_obj->getDate() . ' ' . $time_obj->getTime();
        return $datetime; }}$datetime_obj = new DemoDateTime();
echo $datetime_obj->getDateTime();
Copy the code

Composition: Composition is also a relation of whole and part, but it is a strong aggregation relation. It can be understood that each part can not leave the whole, leaving the problem.

generalization

That’s inheritance.

implementation

An implementation is an abstract class that is implemented by another class.

Interface oriented programming

Generally speaking, it is the use of interfaces, the use of the interface as the framework of the definition, the rest of the details, the implementation of the interface to use, that is, the definition and implementation of the separation, requires the developer to have a separate abstraction.

When to use abstract classes and when to use interfaces?

(The above content is original, the following content is all from the network, and then integrated, thank you for your reply.) Interfaces should have two types: the first type is an abstraction of an individual, which corresponds to an abstract class; The second type is the abstraction of a certain aspect of an individual, that is, the formation of an abstract surface. An individual may have multiple abstract surfaces. Insert Update Select is used as an interface to operate a database. However, the content of each function operation is different. Therefore, create an abstract class inheriting interface and then implement the concrete methods of the abstract class derived from the abstract class.

An interface is a set of rules that specifies the class that implements the interface or the set of rules that the interface must have. The difference between an abstract class and an interface is motivation. Abstract classes are used for code reuse, while interfaces are motivated to achieve polymorphism.

If the concept actually exists in our heads, use abstract classes. Otherwise, if the concept is just a feature of one thing, like something that can fly, something that can run, that’s what we call an interface. When we set it as an abstract class or an interface, we usually set it as an interface, because we implement this interface can also inherit.

Abstract classes are suitable for defining the inherent properties, or essence, of a domain, and interfaces are suitable for defining the extended capabilities of a domain. When you need to provide common implementation code for some classes, you should give priority to abstract classes. Because nonabstract methods in an abstract class can be inherited by subclasses, the code to implement the functionality is simpler. Interfaces are preferred when extensibility and maintainability of code are important. (1) There can be no hierarchical relationship between the interface and the class that implements it. The interface can realize the same behavior of unrelated classes, which is more convenient and flexible than the use of abstract classes. ② The interface only cares about the method of interaction between objects, but does not care about the concrete class corresponding to objects. An interface is a protocol between programs that is safer and cleaner than the use of abstract classes. Interfaces are more commonly used.

Use interfaces when describing a set of methods and abstract classes when describing a virtual object

Abstract classes are “is” related to inheritance classes and interfaces are “like” related to implementation classes. From this perspective, you should see a lot of things. The other differences are just syntax, usage specification differences, and the core idea is this IS-like distinction.