Deep into PHP object-oriented, pattern and practice _javascript skills

Source: Internet
Author: User
Tags error handling inheritance

1 grammar

1.1 Basic syntax

Clone

You need to manipulate the original object, but do not want to affect the original object.

Copy Code code as follows:

$K _back = Clone $K;

Basic data types and arrays are true copies, which are true replicas, and when the attribute is an object, a fake copy will still affect the original object. Solution:

Add
function __clone () {
  $this-> object = Clone $this-> object in the original object

__clone is triggered automatically before cloning, and can perform some property operations before the backup.

2. & Pass Reference

Method reference passing, changing the source object

Copy Code code as follows:

Function Set_k (& $K) {...}
Function & Get_k () {...}

3. Static delay statically binding

Scenario: Both the dog class and the person class need a method to return the instantiation, and both the dog class and the person class inherit from the animal abstract class.

Abstract class animal{public
  static function create () {
    //Instantiate calling class return
    new Static ();
  }
}

Class person extends animal{...}

Returns the person instantiated class
person::create ();

4. Intercepting device

__get ($property) that is invoked when an undefined property is accessed.
__set ($property, $value) is invoked when assigning values to undefined properties.
__isset ($property) called when a Isset () method is called on an undefined property.
__unset ($property) called when a unset () method is called on an undefined property.
__call ($method, $arg _array) Called when a method is invoked.
__call is very useful, but it should be used with caution because it is too flexible.
Scenario: There is a person_writer class that specifically prints the person class information, if the Person_writer class is invoked through the person class.

The person delegate Person_writer class to handle print transactions.
Class Person {
  private $writer;
  ...

  function __call ($method _name, $args) {
    if (methood_exists ($this->wirter, $method _name)) {return
      $this- >writer->method_name ($this);
    }

  Advanced __call, which is used when the parameter of the delegate method is indeterminate.
  function __call ($method _name, $args) {
    //Of course, there is little meaning in this writing, but call is generally called by the Call_user_func_array
    $args = $this;
    if (methood_exists ($this->wirter, $method _name)) {return
      Call_user_func_array
        Array ($this-> Writer, $method _name), $args)
    }
  

5. Callback function

Scenario: 3 classes, Product class, Product_sale class, Product_totalizer class, to implement: output warning when selling Product total price exceeds specified amount.

Product class Product {public $name;
Public $price;

  }//product_sale class Product_sale {private $callbacks; Log callback functions function Register_callback ($callback) {if (! Is_callback ($callback)) {thow new Exception (' Callback N
    OT callable ');
  } $this->callbacks[] = $callback;
    }//Execute callback Functions function sale ($product) {print "{$product->name}: Processing \ n";
    foreach ($this->callbacks as $callback) {Call_user_func ($callback, $product);
    }}//produce_totalizer class Produce_totalizer {static function Warn_amount ($amt) {$count = 0;
      return function ($produce) use ($amt, &count) {$count + = $produce->price;
      print ' Count: {count}\n ' if ($count > $amt) {print "exceeds the specified amount {$amt} ~";
  }
    };
}///simulate scene $product _sale = new Produce_sale (); 

The specified alarm amount is 8 blocks $product _sale = Register_callback (Produce_totalizer::warn_amount (8));
Sell Merchandise $product _sale->sale (new product ("Durex", 6); $product _SALE->sale (New Produce ("Jissbon", 5)); Output Durex: Processing of count:6 Jissbon: processing count:11 over the specified amount of 8 yuan ~

6, Get_class () and instanceof

Get_class (Class) is used to determine whether precision equals class name;

Instanceof can determine whether it itself or inherits from a parent class.

7, methods in the class and properties in the class

Copy Code code as follows:

Get_class_methods (' class name '): Gets all the methods in the class.
Get_class_vars (' class name '): Gets all the public parameters in the class;

8, Reflection API

2 mode

2.1 Combination

Question: Class classes are inherited by lecture classes and seminar classes. But both the lecture class and the discussion class should realize the one-time billing and the N-class billing method. And the way the output is calculated.

Solution 1: Add the method of calculating lump sum to the class of class, the method of billing method of n times and the way of output calculation.

Solution 2: Using the combination, the processing billing and output calculation methods are encapsulated separately into a billing policy class.

Abstract class Cost_strategy {protected $duration;
  Abstract function cost ();

  Abstract function Charge_type ();
  Public __construct ($duration) {$this->duration = $duration;
    } class Timed_const_strategy extends Cost_stratedy {function cost () {//Last lesson to 5 dollars-.
  Return $this->duration * 5;
  function Charge_type () {return "Multiple lesson settlement";
  } class Fixed_const_strategy extends Cost_stratedy {function cost () {return 30;
  function Charge_type () {return "disposable class settlement";

  } abstract class Leason {private $cost _strategy;
  Public __construct (Const_strategy $cost _strategy) {$this->cost_strategy = $cost _strategy;
    function __call ($method _name, $args) {$args = $cost _strategy; if (methood_exists ($this->cost_strategy, $method _name)) {return Call_user_func_array array ($this->write
      R, $method _name), $args);
}}///apply $leasons [] = new Seminar (new Timed_const_strategy (4)); $leasons [] = new LeCture (new fixed_const_strategy (null));
  foreach ($leasons as $leason) {print "Leason charge: {$leason->const ()}"; Print "Charge_type: {$leason->charge_type ()}"} Leason charge 20.
Charge_type: multiple class settlement; Leason charge 30. Charge_type: one class settlement;

A combination of both delegates. Peer delegates.

Inherits both parent-child relationships.

3 Build Objects
3.1 Single case mode

Make sure there is only one use case in the system. For example, system configuration files.

Focus

1: Construction method Private.

2: The class itself contains its own instantiated properties.

Class Preferences {
  private static $instance;
  Private Function __construct () {...}

  public static function Get_instance () {
    if (Empty (self:: $instance)) {
      self:: $instance = new Preferences ();
    } Return
    self:: $instance;
  }
  ...
}

Use
$preferences = Preferences::get_instance ();

3.2 Factory mode

Through a parent class, the production is a subclass of several different functions.

Features: Product side (Sina Weibo) and demand side (show Sina Weibo) one by one correspondence.

Question: In the impression notes, the source may be Sina Weibo, or the developer's headline, when the impression notes are displayed, the headers and footers are different.

3.3 Abstract Patterns

RLGL!!!. Impression notes do not just show Sina Weibo content!!! Also want to show my Sina account, but also to the Micro Bo Ah!! Groove ~ Hold your breath and Kiss me.

Factory mode is mainly used to produce one by one of corresponding products and demand side, and the abstract model to do is a demand side (impression notes _ Sina Weibo), to a number of factories (the demand side abstracted to multiple demand side), such as the company to provide Sina content of the factory, to provide Sina account of the factory. A factory that provides comments on microblogging content.

Code:

Abstract class Show_evernote {
  abstract function get_header_text ();
  Abstract function Get_context ();
  Abstract function Get_footer_text ();
  Abstract function Get_user ();
  Abstract function get_comment ();

}

Class displays Sina Weibo extends show_evernote{
  function Get_header_text () {...};
  function Get_context () {New Sina micro-blog _ content;}
  function Get_footer_text () {...};
  function Get_user () {New Sina micro-blog _ account;}
  function Get_comment () {New Sina Micro Blog _ comment;}
}

Use
impression Note control class-> content = Show Sina Weibo->get_context;
Impression note Control class-> account number = Show Sina Weibo->get_context;
...

3.4 Parallel mode

When using a factory/abstract schema, you must develop a specific creator (demand side).

Parallel and abstract patterns are consistent with the model diagram, but the code implementations are different.

In the abstract schema, the parent class is an abstract class, and in parallel mode, the class is generic and facilitates the instantiation of the parent class.

List the implementation code for the impression note class here

Class show_evernote{
  private $ content;
  Private $ account number;
  Private $ comment;

  function __construct (content, account number, comment) {
    $this-> content = content;
    $this-> account = account number;
    $this-> comments = comments;
  }

  function get_ content () {return
    clone $this-> content);

  function get_ account () {return
    clone $this-> account);

  function get_ Comment () {return
    clone $this-> comment;
  }
}

Use $factory = new Show_evernote (New Sina Weibo content (), new Sina Weibo account () 
  , new Sina Weibo
  review ()
);

Impression note Control class-> Show impression notes = $factory;

In fact, we can find that the prototype model only in the top-level class packaging the various components of the subclass, but this can easily combine them, such as the implementation of a display Sina Weibo content, but to show the developer headline account requirements?

4 Using objects
4.1 Combination Mode

Combined mode, which can be understood as a single object management composite object (aggregation component), the final combination of the various components under the best type consistent. Otherwise the more specific, the more you need to judge.

Suppose the Pat man, the foot-washer man, the shampoo man, is used to serve a person (sister).

Suppose that several parts of a sister can be used for unlimited service men.

Create a sister
$ sister = new person ();

Add foot-washing male, Pat male
$ sister->add_man (new foot-washing man);
$ Sister->add_man (new Pat male);

Loop all men to give a comfortable way.
$ sister-> calculate the degree of comfort ();

This is an ideal combination mode, in reality, we use combination mode, may have to create many types of foot-washing men, need to add a lot of judgment conditions.

4.2 Decoration Mode

Decoration mode, first wash feet male, shampoo male, Pat men are people, but if, a man and Pat, and shampoo, this How to play? Add_man two times? It's not science, let's decorate these men.

Abstract class Person {
  ...
  Abstract function Get_well ();
}  

Class Male extends Person {
  //Whether you are God horse male, serve you, you can obtain 10 points of comfort.
  Private $well = ten;
  function Get_well () {return
    $this->well ();
  }
}

Abstract class decorated male type extends person {
  protected $ person;
  function __construct (person $ person) {
    $this-> person = $ person;
  } 
}

Class Pat decorated extends class Sportsman {
  function Get_well () {return
    $this-> person->get_well () +30;
  }

} Class Shampoo decorative extends class of sportsman {
  function Get_well () {return
    $this-> person->get_well () +20;
  }
}

Class wash fade decorate extends class of sportsman decorate {
  //I don't like others to touch my maoku.
  function Get_well () {return
    $this-> person->get_well () -20;
  }
}

Create a pat, can give the comfort index-Hee XI.
$ man = new Pat decoration (new man);
$ person->get_well (); 10+30 =

//Come, all-around player, Pat, shampoo, wash your legs.
$ man = new Shampoo (New Pat Decoration (New Man ()),//10+30+20-20 = 40, note order, from inside to outside.

Decorative mode, both (combination + inheritance), the base class method must be as little as possible, or subclasses may have its own methods. Direct class inheritance, she may only be a form, and her many forms may be possessed together, should use the combination.

Inheritance is a single polymorphism that combines multiple polymorphic states.

In this example, you can add a female, and then change the decorated male type to an ornamental generic type, but each get_well () should be judged by a male or female (if given a different level of comfort).

This is just to make sure that there is no such a third person, if the base class is an animal, the service may be chicken, goose, duck, then the decorative type should be used in Factory mode, animal shape and decorative form one by one correspond. Easy to expand.

In addition to service types, the appearance of service men is also very important, this is more than a decoration, there are now decorated male types and appearance of male types, this situation how to break, in fact, similar.

Copy Code code as follows:

How to get Pat's handsome Mike?
$ man =new male type (new Pat (New Congome ()));

4.3 appearance mode

Provides a clear interface to the external system

For example, when the model layer is written in a very confusing way, but the methods are still available, our controller layer should enumerate some clear access methods for the view level access. The appearance pattern emphasizes the clear access interface.

5 Perform the task
5.1 Policy mode

Add functionality to the class. Object to invoke it explicitly.

Continue the story of the man who washed the feet just now ... You're going to pay for that, aren't you? Paying treasure? Micro-letter cash?

This method of payment has a variety of ways, the implementation should not be placed in humans, but should be entrusted to other classes

Abstract class Person {

  PROTECTD $ payment method;

  Function set_ Payment method () {...}

  function payment (amount) {return
    $ payment Method-> Payment ($ amount);
  }

Abstract class Payment {
  abstract function payment ($ amount);
}

Class Alipay payment extends Payment {

  function payment ($ amount) {return
    external Alipay payment process ($ amount);
  }
...

Use
$ male =new male ();

Shuangshuang Cool
...

Checkout
$ Alipay Payment bill = new Alipay payment ($ amount);
$ man = new Man ();
$ person->set_ Payment Method (new Alipay payment ());
$ person-> payment ();

5.2 Observer Mode

When the observed changes, the observer needs to be notified.

When data is changed, the page needs to be notified.

Use steps:

The observer is loaded into the viewer.
The Observer is informed of the observer.

For example the landing class (observed) the state changes, to start the mail system and the log System (Viewer)

Interface is observed {function attach (Observer);
  function Detatch (Observer);
function notify ();

  Class Login implements is observed by {private $ observer;
  function __construct () {$this-> observer = array (); 
  function attach ($ observer) {$THIS-> observer = $ observer;
  function detach ($ observer) {//delete an observer's operation;
    function Notify () {foreach ($this-> Observer as $ single observer) {$ single observer->update ($this);

}} interface Observer {function update (observed);}
  Abstract class Login_ observer implements Observer {private $login;
    function __construct (Login $login) {$this->login = $login;
  $login->attach ($this);
    Function update (Observer $ observer) {if ($ observer = = = $this->login) {$this->do_update ($ observer);
} abstract function Do_update (Login $login); Class Mail Observer extends login Observer {function do_update (Login $login) {//Judge condition Send mail}} Class log observer extends login Observer {F
  Unction do_update (Login $login) {//Judgment condition recorded to log;
}///Use $login = new Login ();
New Mail Viewer ($login); New logObserver ($login); 

PHP has built-in SPL to implement the above observer pattern.

5.3 Visitor Mode

Problem: In an army, there are a lot of troops, the Army may contain the Army/infantry/archers, then we want to show an army's fighting capacity/need for food distribution at all levels? (Iterate over the object and set the display method). What to do? The solution is for the army to save its own basic information, set up a visitor, the visitor includes the total combat effectiveness method and the total food method.

Visitors

Abstract class Army Visitor {
  Abstract function access (unit);

  Function Access Army ($ army) {
     $this-> access ($ army);
  }
  Function Access Archer ($ archer) {
    $this-> access ($ archer);
  }

  A lot of code is duplicated here, but you can use call instead of
  function __call ($method _name, $args) {
    if (Strrpos ($method _name, Access)) {
      Return Call_user_func_array (
        array ($this, access), $args
      );

}} Class Army combat Effectiveness visitor extends Army visitor {
  Private $text = "";

  function access ($ unit) {
    $ret = "";
    $pad = 4*$ Unit->getdpth (); Setting shows 4 more spaces before the depth level.
    $ret. = sprintf ("%{$pad}s", "");
    $ret. = Get_class ($ unit). ": ";
    $ret. = "Combat effectiveness:". $ unit->bombardstrenth (). \ n ";
    $this->text. = $ret;
  }

  function Get_text () {return
    $this->text;
  }
}

by visitors

Abstract class Unit {
  function accepts ($ army visitor) {
    $method = "Access _". Get_class ($this);
    $ Army Visitor-> $method ($this);
  }

  Private $depth;
  protected function Set_depath ($depth) {
    $this->depth= $depth;
  }

  function get_depth () {return
    $this->depth;
  }
  ...
}

Abstract class synthesis unit extends cell {
  function acceptance ($ army visitor) {
    Parent:: Accept ($ army visitor)
    foreach ($this-> unit set as $ This_unit) {
      $this->unit-> accept ($ army visitor);
    }
  }

Class Army extends integrated unit {
  function bombardstrenth () {
    $ret =0;
    foreach ($this-units () as $unit) {
      $ret + + $unit->bombardstrenth ();
    }
    Return $ret
  }
}

class Archer extends cell {
  function bombardstrenth () {return
    4;
  }
}

Call

$main _army = new Army ();
$main _army->add_unit (New Infantry ());
$main _army->add_unit (New Archer ());

$ Army Combat Effectiveness Visitor _ Example =new Army Combat Effectiveness Visitor ();
$main _army-> Accept (equal combat effectiveness visitor);
Print $ army Combat Effectiveness Visitor->get_text ();

Output

Copy Code code as follows:

Army: Fighting Power: 50
Infantry: Attack: 48
Archer: attack: 4

5.4 Command mode

Example for Web page login and Feed_back, if all need to use AJAX submission, then the problem, the form package to submit up, get the return results. How do I jump to different pages based on the return result?

Some students said, login and Feed_back each write a method to suppress, submit the time to call their own methods.

And then a logout order. Increase.. Delete.. What to do with the order.

Command mode is better suited to command execution such as landing, feedback, etc. simply to determine whether a successful task

Command:

Abstract class command{
  abstract function Execute (conmmand_context $context);

Class Login_command extends command{
  function execute (commandcontext $context) {
    $managr =register:: Getaccessmanager ();
    $user = $context->get ("username");
    $pass = $context->get (' Pass ');
    $user _obj = $manager->login ($user, $pass);
    if (Is_null ($user _obj)) {
      $context->seterror ($manager->geterror ());
      return false;
    }
    $context->addparam ("User", $user _obj);
    return true;
  }

The caller of the deployment command

Class command_facotry{public
  function Get_command ($action) {
    $class = Ucfirst (Strtolower ($action)). " _command ";
    $cmd = new $class ();
    return $cmd;
  }

Client

Class controller{
  private $context;
  function __construct () {
    //command_context is primarily used to store request and params
    $this->context =new command_context ();
  }
  function Process () {
    $cmd Command_factory::get_commad ($this->context->get (' action '));
    if (! $cmd-execute ($this->context)) {
      //error handling
    }else{
      //Successful distribution view
    }
}}

Use

$controller =new Controller ();
$context = $controller->get_context ();
$context->add_param (' action ', ' login ');
$context->add_param (' username ', ' 404_k ');
$context->add_param (' Pass ', ' 123456 ');
$controller->process ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.