PHP core technology and best practice knowledge points (top)

Source: Internet
Author: User
Tags bulk insert parse error php source code

I. Basic

1.serialize: Serialize a class, just save the properties of the class, so you also need to deserialize the unserialize when the class is included.

2. For converting an array to object, this conversion is called an orphan class because there is no specific class:

<?php$arr = [1,2];var_dump ((object) $arr); Output object (StdClass) #1 (2) {  [0]=>  int (1)  [1]=>  Int (2)}

  

3. The polymorphism of other languages is the upward transformation, the polymorphism of PHP has not been transformed, just called the different derived classes.

4. The interface is a contract, but the PHP interface does not have the ability to constrain.

Interface engine{public    function run (); Class Car implements engine{public    function run ()    {        echo ' run '. Php_eol;    }    Public Function Fly ()    {        echo ' fly '. Php_eol;}    } function check (Engine $e) {    $e->fly ();} $car = new car (); check ($car);

  

We indicate in the function check that the passed in parameter should be an engine-compliant interface constraint, but it does not actually play this role. PHP only cares if the incoming object implements the method defined in the interface, and does not care if the semantics of the interface are correct.

5. To compensate for the lack of multiple inheritance in PHP, PHP has introduced trait since php5.4.0, which enables code reuse. Trait can be seen as an enhanced interface

Trait HelloWorld {public    function SayHello () {        echo ' Hello world! ';    }} Class Theworldisnotenough {use    HelloWorld;} $o = new Theworldisnotenough (); $o->sayhello ();

  

6. Reflective Api:reflectionclass

7.tokenizer
The Tokenizer function provides a calling interface embedded in the Zend engine's "PHP tokenizer". Using these functions, you can write your own PHP source code analysis or modify the tool without having to deal with the language specification at the lexical analysis level.

Example code: $tokens = Token_get_all (' <?php echo 1;?> ');p rint_r ($tokens);

  

Error in 8.php means that the script is not working properly and the exception is that the business process is not working properly. Exceptions in PHP need to be thrown manually, meaning it is not very large.

9.set_error_handler (): Custom error, error suppressor invalid if custom error.

function handler ($errorNo, $ERRORSTR, $errorFile, $errorLine) {die    ($ERRORSTR);} Set_error_handler (' handler ', e_all); @ $a [500];

  

An example of custom errors and exceptions that you want to combine:

function handler ($errorNo, $ERRORSTR, $errorFile, $errorLine) {    throw new Exception ($ERRORSTR, $errorNo);} Set_error_handler (' handler ', e_all); try {    @ $a [];} catch (Exception $e) {    echo $e->getmessage ();}

  

10. Catch fatal error fetal error:register_shutdown_function

function shutdown () {    //echo error_get_last ();    echo ' OK ';} Register_shutdown_function (' shutdown '); A;

  

When a fatal error occurs, the shutdown is recalled, providing some remedial opportunities, but the termination of the program is inevitable.

11. Syntax error (parse error) Processing: Register_shutdown_function does not handle syntax errors when counted in the log.

Php.inilog_error=onerror_log=/usr/log/php-error.log

  

12. Trigger Error: Trigger_error

<?phpfunction Test () {    trigger_error (' Manual trigger Error ');} Test ();

  

13. A basic object-oriented example:

//domainclass message{Public Function setmsg () {} public Function ge Tmsg () {}}//Modelclass messagemodel{//Read public function from the database read () {}//write public from database Functio  N Write (Message $data) {}//Paging Public Function page () {}}//logical layer class logicmessage{public function    Write (Messagemodel $model, Message $data) {$model->write ($data);    Public Function view (Messagemodel $model) {return $model->read ();         }}//Controller class actionmessage{Public function write (Logicmessage $logicMessage, Messagemodel $model, Message $data) {    $logicMessage->write ($model, $data);    Public function read (Messagemodel $model) {return $model->read (); }}//Call $message = new Message (), $logic = new Logicmessage (), $model = new Messagemodel (), $action = new Actionmessage (); $act Ion->write ($logic, $model, $message) $action->read ($model); 

  

14.ignore_user_abort (TRUE); Even if the user closes the Web page, the program executes in the background without interruption.

Two. HTTP protocol

1.cookie
Server sent to client using: Set-cookie header
Client sends a cookie header to the server

The difference is that the value of the cookie header can have multiple cookie values and does not require domain designation; Set-cookie can have only one value and need to indicate path and domain

2.ip is passed in the TCP layer, so http_client_ip or REMOTE_ADDR in the server variables in PHP are hard to forge. And Http_x_forwarded_for comes from the X forwarded in the HTTP request For header, and this header can be modified.

Three. CUrl
curl, asynchronous execution: $ch 1 = curl_init (), $ch 2 = Curl_init (); curl_setopt ($ch 1, Curlopt_url, ' http://www.baidu.com '); curl_setopt ($ch 1, curlopt_header, 0); curl_setopt ($ch 1, Curlopt_returntransfer , 1); curl_setopt ($ch 2, Curlopt_url, ' http://news.baidu.com '); curl_setopt ($ch 2, Curlopt_header, 0); curl_setopt ($ch 2, Curlopt_returntransfer, 1); $mh = Curl_multi_init (); Curl_multi_add_handle ($MH, $ch 1); Curl_multi_add_handle ($MH, $ch 2 );//execute batch do {$MRC = Curl_multi_exec ($MH, $active),} while ($MRC = = Curlm_call_multi_perform); while ($active and $MRC    = = CURLM_OK) {if (Curl_multi_select ($mh) = = = 1) {usleep (100);    } do {$MRC = Curl_multi_exec ($MH, $active); } while ($MRC = = Curlm_call_multi_perform);} Get content $content1 = curl_multi_getcontent ($ch 1), $content 2 = curl_multi_getcontent ($ch 2);//remove handle, otherwise cause a dead loop curl_multi_ Remove_handle ($MH, $ch 1); Curl_multi_remove_handle ($MH, $ch 2), Curl_multi_close ($MH), Echo $content 1;echo $content 2; 

  

Four. Cookies

The difference between 1.setrawcookie and Setcookie is that the former does not urlencode the value

2.php does not set a cookie, just notifies the browser to set the Cookie.cookie settings on the current page will not take effect, on the next page will not take effect.

3.cookie is part of the HTTP header, so there is no output until the cookie is set.

4. The allowed cookies under each domain name are limited, IE8 is 50, Firefox is 150

5. Each cookie limit size of a domain name is 4KB

Five. Session

The session.save_path= "N" in the session setting in 1.php.ini; Mode;/path "
N: Indicates the level of the directory, such as 2 for 2 levels of directory storage, each level has 0-9 and a-Z a total of 36 characters as a directory name, 2 can have 36*36 directory
MODE: Indicates directory permissions, default is 600
Path: Indicates the storage path

2. The session,php for setting up a tiered directory store will not be automatically recycled, you need to implement the recycling mechanism yourself

3. Access to a large site, the default file session is not appropriate, you can use the database or memory cache

Six. 10 principles of Basic SQL optimization

1. Avoid operations on columns, which will invalidate the index.
SELECT * FROM table WHERE year (d) > 2017;

Optimized for
SELECT * FROM table WHERE d > ' 2017-01-01;

2. With join, a small result set drives a large result set and splits a complex join query into multiple queries. Because joins multiple tables, it causes more locking and blocking.

MySQL automatically drives large result sets with small result sets when connected.
Left junction and right junction, you need to make optimization

3. Avoid the fuzzy query like
SELECT * from user where username like '%u% ';

Optimized to:
SELECT * from user where username >= ' U ' and username < ' V ';
Or
SELECT * from user where username like ' u% ';

4. List only the required fields, which have no effect on speed, mainly consider saving memory.
SELECT * from user where username >= ' U ' and username < ' V ';

Optimized for
Select ID from user where username >= ' U ' and username < ' V ';

5. Use BULK Insert to save interactivity
Insert into table values (' A ', ' B ', ' C ');
Insert into table values (' A ', ' B ', ' C ');
Insert into table values (' A ', ' B ', ' C ');

Optimized to:
Insert into table values (' A ', ' B ', ' C '), (' A ', ' B ', ' C '), (' A ', ' B ', ' C ');

Use between when the 6.limit cardinality is relatively large
SELECT * from the user order by ID ASC limit 1000000,10

Optimized to:
SELECT * from user where ID between 1000000 and 1000010 ORDER by ID ASC

However, if there is a break, the entry will not apply.

7. Do not use Rand to return random data.

8. Avoid using null,mysql difficult to optimize queries that reference nullable columns

9. Use COUNT (*) instead of count (ID)

10. Do not make unnecessary sorting operations, as far as possible in the index to complete the sorting.

Seven. MySQL

1.explain: Guaranteed type reach range level, preferably ref level, all for full table scan, this is the worst case
2. Simply determine the read/write ratio (R/W):
Show global status;

Com_select for reading, Com_update+com_insert for writing
If r/w is less than 10:1, it is considered to be a write-based database.


3.MyISAM: Appropriate increase key_buffer_size; can be calculated according to the key_cache hit rate
Show global status like ' key_read% ';

Cache misses: Key_cache_miss_rate=key_reads/key_read_requests * 100%, if greater than 1% should be appropriately increased key_buffer_size

Also note the settings of the Table_cache. If the value is too small, MySQL will open it repeatedly and close the frm file. If it is too large, it will cause a waste of the CPU. A reasonable approach is to observe the value of opened_tables, and if it continues to grow, increase the Table_ The value of the cache.


4.InnoDB: Focus attention on innodb_buffer_pool_size;

5. Optimize table tableName can be run when a large number of rows are removed from the table;

Eight. mysql analog Message Queuing


0: Process:
Users post an article (insert into article), trigger Tigger_insert_feed, insert a dynamic into the feed table, trigger Tigger_insert_queue, Timer event_push_ Broadcast extracts data from the queue every 1 minutes to feed_broadcast.

1. Create a new user table
CREATE TABLE ' user ' (
' id ' int (one) not NULL auto_increment,
' Name ' char (255) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT CHARSET=GBK;

2. New Friend table
CREATE TABLE ' friend ' (
' id ' int (one) not NULL auto_increment,
' UID ' int (one) DEFAULT NULL,
' Fuid ' int (one) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT CHARSET=GBK;

3. New Feed_broadcast
CREATE TABLE ' Feed_broadcast ' (
' id ' int (one) not NULL auto_increment,
' UID ' int (one) DEFAULT NULL,
' title ' char (255) DEFAULT NULL,
' Is_read ' tinyint (4) DEFAULT ' 0 ' COMMENT ' is read ',
' Time ' int (one) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT CHARSET=GBK;

4. New Article table
CREATE TABLE ' article ' (
' id ' int (one) not NULL auto_increment,
' UID ' int (one) DEFAULT NULL,
' title ' char (255) DEFAULT NULL,
' Time ' int (one) DEFAULT NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT CHARSET=GBK;

Set up Trigger Trigger_insert_feed
Create trigger Trigger_insert_feed after insert on article for each row
Begin
Insert into feed (uid,article_id,content,time) VALUES (New.uid, New.id, ' published article ', new.time);
End

5. Create a new feed table
CREATE TABLE ' feed ' (
' id ' int (one) not NULL auto_increment,
' UID ' int (one) is not NULL,
' article_id ' int (one) is not NULL,
' Content ' varchar (+) not NULL,
' Time ' int (one) is not NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT CHARSET=GBK;

Set up Trigger Trigger_insert_queue
Create trigger Trigger_insert_queue After insert in feed for each row
Begin
Insert into queue (Uid,feed_id,content,status,time) VALUES (New.uid,new.id, ' published article ', 0,new.time)
End

6. Create a queue table:
CREATE TABLE ' Queue ' (
' id ' int (one) not NULL auto_increment,
' UID ' int (one) is not NULL,
' feed_id ' int (one) is not NULL,
' Content ' varchar (+) not NULL,
' Status ' tinyint (4) not NULL DEFAULT ' 0 ' COMMENT ' 0 is not processed, 1 is processing ',
' Time ' int (one) is not NULL,
PRIMARY KEY (' id ')
) Engine=innodb DEFAULT CHARSET=GBK


7. Create a stored procedure push_broadcast:
CREATE definer= ' root ' @ ' localhost ' PROCEDURE ' push_broadcast ' ()
BEGIN
Insert into Feed_broadcast (uid,title,time) Select Ef.fuid,tmp.content,tmp.time from (SELECT * from queue where status=0 or Der by id desc limit ten) Tmp,friend ef where tmp.uid=ef.uid;
Update queue set Status=1 where status=0 ORDER by id desc limit 10;
END

8. Create a timed event Event_push_broadcast:
CREATE definer= ' root ' @ ' localhost ' EVENT ' event_push_broadcast ' on SCHEDULE every 1 MINUTE starts ' 2017-11-12 17:53:58 ' on Completion not PRESERVE ENABLE does call Push_broadcast ()


See if Event_scheduler is turned on
Show global variables like '%sche% ';

If the event_scheduler is off;
Open:
Set global event_scheduler=on;

9. Now you can insert the data to do the test

PHP core technology and best practice knowledge points (top)

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.