PHP Advanced Knowledge Summary

Source: Internet
Author: User
Tags bulk insert delete key php memcached

The weekend combing the next time to read some of the knowledge points, the process of progress not only to practice, but also to arrange more reading, thinking, summary.

Only for the knowledge point of the list and simple description, a lot of details have not been sorted out, to be followed by a special detailed writing.

Basic easy to ignore concept

PHP is a language that supports object-oriented development, rather than a purely object-oriented language, the support for Var is preserved in PHP5, but Var is automatically converted to the public type check function:
Is_bool ()is_integer()is_double()is_string()Is_ Object()is_array()is_resource()is_null()
PHP Magic Method:
__call () __callstatic () (     must be a static property) __set () __get () __isset () __clone () __tostring ()
The string "False" resolves to true when comparing operations, because PHP converts a non-empty string value to a bool value when a variable is tested, and a static method is a function that is scoped to the class. Static methods cannot access normal properties in this class, because those properties belong to an object, but you can access a static property (you cannot use a pseudo-variable in a static method $this) The Constant property contains only the values of the base data type and cannot assign an object to the constant abstract class (abstract class) cannot be instantiated directly, only defined (or partially implemented) subclasses require the method abstract class contains at least one abstract method static is similar to self, but it refers to the class being called instead of the containing class return new static () Copying Objects(prototype mode in design mode):
$first New ClassName (); $second $first ; // in later versions of PHP5, $second and $fitst point to the same object $third Clone $first;          // use clone for "value copy"//in PHP5 versions, $third and $first are two different objects /* control what to replicate:          You can implement a __clone () method          such as having a $id=1 in the object to be copied, but we want this ID to be unique, and you do not want to clone this ID, you can implement the Clone method in your class */  

callback, anonymous function:
is_callable (); Call_user_func ($funcName,$param);     // single parameter Call_user_func_array ($funcName,$arrParam);     // parameter is the form of an array
namespace namespace:A namespace is a container that, outside of a namespace, must import or reference a namespace to access the items it contains.
namespace Com\name\test1; class debug{    staticfunction  Test ();}
namespace Test2; // Call the test method \com\name\test1\debug::test () in the Test1 namespace ;     // The first must be added/otherwise you will find this namespace under Test2  Use com\name\test1;test1\debug:: Test ();  
Resolve class naming conflicts:
 Use  as Udebug; class debug{... }udebug::Test (); __namespace__     // output Current namespace

Namespaces are enlarged in parentheses:

namespace com\name\test1{    class debug1{... }    class debug2{... }}

require () when an error occurs in the calling file, the entire program is stopped.

Call include ()When encountering the same error, it generates a warning and stops executing the include file, jumping out of the calling code and then continuing. Require () and require_once () are more secure when containing library files, include () and include_once () apply to to load templates relative to require () functions, require_once () require additional overhead Auto Load AutoLoad:When the PHP engine encounters an operation that attempts to instantiate an unknown class, it calls the __autoload () method (which is defined in advance) and passes the class name as a string parameter, for example:
function __autoload ($className) {    // to convert an underscore in $classname to a directory split    $pathstr_replace(' _ ', Directory_separator,$className);     require_once ("$path. php");}

The __autoload method is an efficient way to manage the class library file containment based on the class and file structure.

class functions:
class_exists();get_declared_classes();//get an array of all classes defined in the script processGet_class($obj);//check the class of the object, check the class to which the object belongs$objInstalceof ClassName;//Checking Objects Get_class_methods();//get a list of all the methods in a class is_callable()、method_exists()//checks if the class method exists and can be called#a method exists that does not consider callable, and returns true for private, protected, public methods, Method_exists () Get_class_vars($className);//gets the properties defined in the classGet_parent_class($classNa, e);//gets the parent class of a classis_subclass_of($className, ' Classstrname ');//to check if a class is a derived class of another classclass_implements($className);//returns an array that consists of an interface name
Reflection APITo find the origin and source according to the arrival point, reflection refers to extending the parsing PHP program in PHP running state, exporting or extracting detailed information about classes, methods, properties, parameters, etc., including comments. This dynamic access to information and the ability to dynamically invoke object methods, called the Reflection API, use the reflection API to scan classes in a file, generating profiles the Five Principles of object-oriented design:
    1. Single principle of responsibility
    2. Interface Isolation principle
    3. Open-closed principle
    4. Replacement principle
    5. Dependency-Inversion principle
10 Principles of SQL optimization:
    1. Do not perform function operations on columns, resulting in index failure
    2. When you use join, a small result set is applied to drive a large result set. Splitting a complex join query into multiple SQL
    3. Avoid percent of percent when using like fuzzy queries, can be replaced by <=, >=
    4. Only the required fields are listed after the SELECT, which has no noticeable effect on speed, mainly considering saving memory
    5. Use BULK INSERT statements to save interactivity than performing a single insert in sequence
    6. Limit technology is relatively large when considering the use of between
    7. Do not use the RAND function to get multiple random records
    8. Avoid using null
    9. Do not use COUNT (ID), but count (*)
    10. Complete sorting in the index whenever possible
the three elements of a cache:
    1. Shooting
    2. Cache Update Policy
    3. Cache Maximum Data volume
The usual cache update policies are:
    1. FIFO (advanced first Out)
    2. LRU (least recent elimination strategy)
    3. LFU (Minimum use of elimination strategy)
MySQL's Query cache uses the maximum amount of data in the FIFO policy cache to be able to handle the maximum number of elements in the cache or the maximum storage space that can be used exceeding the maximum amount of data allowed by the caching mechanismThe system will be processed accordingly, generally processing ModeYes:
    1. Stop the cache server and empty all cached data
    2. Write rejected, no more updates to cached data
    3. Purge old data based on cache update policy
    4. Backup of retired data based on a 3 approach
opcode cache:The virtual machine compiles the PHP code into an intermediate code and caches it, and the next time PHP runs this page, just explain the code directly. Eaccelerator tools can act as resident Memory client cache, HTTP cache (pending recording) application Cache in H5:Used to deal with problems in offline applications, users can still browse the entire site when they are not connected to the Web need to specify whether the page needs this cache in HTML: Memcached Using memcached:
    1. High concurrency Read and write to the database
    2. For massive data processing
Memcached is a high-performance distributed memory cache server that reduces database access times by caching database query results. Memcached Features:
    1. Simple protocol
    2. Libevent-based event handling
    3. Built-in memory storage mode
    4. The use of non-mutual communication distributed
    5. Run in daemon mode with one or more servers
    6. Memcached using the LRU algorithm to retire data caches
    7. Data persistence is not supported
memcached data is stored in memory, so restarting the memcached or operating system will cause the data to disappear. Installation Memcached:apt-get install memcached start memcached:memcached-d-M 128 -U root-p 11211-d: Daemon Run-M: sets the amount of memory that memcached can use, in Mb-l: Set the IP address of the listener, which can default to-u: Specify the user-P: Set the listening port, default to 11211Install php memcached extension: sudo apt-get install Php5-memcache Some methods of memcached extension:
    • Memcache::connect (string $host [, int $port [, int $timeout]]); Connect a MEM Server
The $timeout is the connection duration, which defaults to 1 seconds. An excessive amount of time will invert the benefits of losing all of the cache
  • Memcache::addserver (String $host [, $port [, $bool $persistent [, $weight [, int $timeout [, int $retry _interval [, Bo     OL $status [, Callback $failure _callback]] []]; Add a server to an object
  • Memcache::add (String $key, $mixed $var [, int $flag [, int $expire]]); Adding cached data
    • The key cannot exceed 250 bytes in length,
    • var value is 1MB max
    • $flag whether to use zlib compression, set to memache_compressed using compression
    • $expire cache expiration time, 0 means no expiration. Setting cannot be greater than 2592000 (30 days)
  • Memcache::replace (String $key, mixed $var [, int $flag [, int $expire]]); Replace a key that already exists
  • Memcache::set (String $key, mixed $vsar [, $flag [, $expire]])//add and replace aggregates
  • Memcache::get (String $key [, int &flags]); Get Cache contents of key
    • $flags if given this parameter (passed by reference), the parameter is written to some information corresponding to the key
  • Memcache::d elete (String $key [, $timeout]); Delete Key's cache
  • Memcache::flush (void); Immediately invalidates all existing caches
    • Do not really release any resources, only marked as invalid
  • Memcache::getserverstatus (String $host [, $port]); Get the online/offline status of a server
  • Memcache::getstats ([string $type [, $slabid [, int $limit = 100]]); Get statistics for a server
  • Memcache::close (void); To close a connection to a memcache server
Memcached using a multiplexed I/O model (such as Epoll, select), the system in traditional blocking IO may be waiting for a user connection to be ready for IO until the connection is ready, if the other user is connected to the server at this time, may not be appropriate because the system is blocked. Multiplexing I/O is a message notification pattern, and when the user connects to IO preparation, the system notifies the connection that it can perform IO operations so that it does not block the connection to a user. Memcached uses the slab allocation algorithm to save the data slab allocation algorithm is the principle of the fixed size (mem default 1M) memory divided into n blocks, each 1M size of memory block is called a slab page, each request to the system a slab page, Then divide the slab page into small chunks of chunk, and then assign the chunk to the user using the segmentation algorithm. Memcached Multithreaded Model:
    • Main thread: Accept the client connection and assign the connection to the worker thread to process
    • Worker threads: Processing requests for client connections
memcached Distributed Layout Scheme:
    • Normal hash distribution
    • Consistent hash distribution
Redis Redis loads the entire database into memory, and periodically flush the database data to the hard disk by asynchronous operation Reids Features:
    1. Support for rich data types: String, List, Sort, Sorted Set, Hash
    2. Support for data persistence: Memory snapshots, log append
    3. Support for master-slave replication
Installing redis:http://www.cnblogs.com/fslnet/p/3759284.html install PHP extension redis:sudo apt-get install Php5-redisredis default port is: 6379     Redis config file (pending) Redis key related commands: Exits key//key exists, returns 0/1del Key1 Key2. Deletes the specified key, returns the number of deleted keys, 0 means the key does not exist type key//returns the value type of the given key, none means that there is no keytypes pattern//Returns all Keyexpire key sec that matches the specified pattern Onds//Sets the expiration time of the specified key Randomkey//Returns a random key in the current database, if the database is empty, returns an empty string rename Oldkey newkey//rename Keyrenamenx Oldkey new Key//Rename key if Newkey exists return failure TTL key//returns set expiration time remaining seconds of key,-1 means key does not exist or does not set expiration time move key db-index//move key from current database to specified number According to the library, return 1 success, 0 indicates that it does not exist or has not been continued in the specified database ...

PHP Advanced Knowledge Summary

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.