In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how PHP encapsulates pdo, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
I. Preface
Recently, we need to write a script to store the crash log, which is unsurprisingly separated from the framework, so OK, we have to encapsulate the database-related operations ourselves. Here we choose to encapsulate the pdo operation database related.
Second, why choose pdo
As we all know, php was extended with mysql in the early days, but then the primary key went down because it was too old and lacked the new features of mysql.
Starting with php5, it is recommended that you use the mysqli extension, which is an enhanced version of the mysql extension and is an object-oriented MySQL interface that is easier to use. The disadvantage is that you can only operate mysql, not strong enough.
And then there is the pdo extension, which is the most abundant extension that supports a variety of databases, and importantly, it is stronger in security than the other two extensions, and it is more effective to prevent sql injection by using prepared preprocessing. Therefore, the blogger chose to encapsulate pdo-related operations here.
3. The persistent connection of pdo 1. What is the persistent connection of pdo
As the name implies, long connection means to keep the connection all the time. Compared with the usual short connection, each request will recreate the link. Long connection can effectively reduce the creation process and better save performance.
In operation, when connecting to the database, add one more parameter:
$pdo = new PDO ($dsn, $username, $passwd, [PDO::ATTR_PERSISTENT = > true])
The following PDO::ATTR_PERSISTENT = > true is the way to open a persistent connection.
2. Is the persistent connection invalid for nginx?
Is it true that bloggers are searching for knowledge about persistent connections when they see an article that concludes that persistent connections only apply to apache, not nginx?
Reference blog address: https://www.cnblogs.com/wpjamer/articles/7106389.html
The general conclusion is: persistent connections are more aimed at apache, because apache maintains a process pool. When apache mpm is enabled, apache will maintain a process pool by default. Connections after mysql persistent connections are not closed as socet connections, but are put into the process pool / thread pool as an unreleased thing.
For nginx, persistent connections are invalid, and resources are freed at the end of script execution.
3. Long connection test under php-fpm
Here the seniors have been tested, we give the address of the seniors, if you are interested, you can have a look.
Reference blog address: https://hacpai.com/article/1526490593632
Conclusion:
It turns out that php-fpm can achieve persistent connections, but if the process is idle, it will result in a waste of resources.
The configuration file of php-fpm can consider setting pm.max_requests = 1000, which represents the maximum number of requested services for each child process. If this value is exceeded, the child process will be automatically restarted.
For example, if the parameter max_requests is set to a large value, the child process will not restart until it is run many times. If there is an error or memory leak in the request, it is not appropriate to set a large value. However, if there is no problem with the request, if the value is set small, it will be restarted frequently, and there will be a lot of 502 problems, so it should be set by different people and wise people. Here, the initialization setting is 1000. If there are no memory leaks and other problems in the test, it can be bigger.
4. The impact of persistent connections on transactions. Reference blog address: https://www.zhihu.com/question/62603122
Summary: if the business concurrency is high and there are transactions, it is not recommended to use a long connection.
5. Summary
In the constant search, bloggers find that connection pooling is always inevitable for long connections to achieve the best performance, and it is a bit of a pity that php cannot implement connection pooling very well.
On the whole, the perfect connection pool with mysql cannot be configured in php. In places where the business is more complex, it is prudent to try long connections. Each connection is a thread, which will result in a lot of waste of resources.
If some businesses require continuous database operations, such as submitting log APIs, you can consider opening persistent connections. Remember to set max_requests to quantitatively close php-fpm connections. After fpm closes, mysql connections will be automatically released.
And pm.max_spare_servers sets the maximum number of php-fpm processes when the server is idle.
For example: pm.max_spare_servers = 25 if you are idle, you will check the number of processes. If you have more than 25 processes, you will close several processes and reach the status of 25.
Students who are good at swoole can refer to this article:
Implementation of real PHP database connection pool based on swoole extension
IV. Encapsulation of pdo part of demo
First of all, this part of the blogger refers to the package of a netizen, and the github address is as follows:
Https://github.com/nadirvishun/php-pdo-class
The basic additions, deletions, modifications and queries of this netizen have been sealed, and they all have parameter preprocessing, so the security is OK. However, since it serves as a benchmark class, there is still something missing.
1. Disconnection reconnection mechanism
For example, reconnect function:
/ * * @ params: reconnect function, up to 3 times * @ date:2020/3/18 * @ time:17:03 * / public function customConnect () {try {$this- > pdo = new PDO ($this- > config ['dsn'], $this- > config [' username'], $this- > config ['password'], $this- > config [' params']) $this- > pdo- > setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); / / need to change the error handling mode to exception mode return true;} catch (Exception $e) {if (stripos ($e-> getMessage (), 'MySQL server has gone away')! = = false | | stripos ($e-> getMessage (),' bytes failed with errno=10053')! = false) {$this- > close () $this- > tryNums++; if ($this- > tryNums > 3) {return false;} self::customConnect ();} else {$this- > throw_exception ($e-> getMessage ()); return false;}} 2, convert php warnings to try … Catch trapable errors
The reason for this is that persistent connections frequently cause mysql gone away errors, which are warnings-level errors of php and cannot be caught by try..catch at all, so bloggers customize error handlers here to handle them.
This part is to convert warnings errors of php into error errors that can be caught by try..catch. We will discuss the error reporting mechanism and error handling of php in the next part.
/ / Custom warnings handler set_error_handler ('customException'); / / after getting the warnngs error, it is converted to an error error and thrown, so that the function customException ($error_no, $error_msg, $error_file, $error_line) {throw new\ Exception ($error_msg,0,null); / / throw new\ Exception ($error_msg) can be captured by try..catch. 3. Reclaim resources by destructing method / * destruct closes database connection * / public function destruct () {$this- > pdo = null;} 4, ping public function query ($sql = null, $param = null) {/ / check whether the connection is active $this- > pdo_ping () when query / / determine whether there is a result set if (! empty ($this- > PDOStatement)) {$this- > free () } xxxxxxxxxx} Thank you for reading this article carefully. I hope the article "how to encapsulate pdo in PHP" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.