Clever overload magic method _ call ()

Source: Internet
Author: User
: This article mainly introduces the clever overload magic method _ call (). If you are interested in the PHP Tutorial, refer to it. After half a year of work, I feel that I have learned more things in the past six months than I have learned in the university for four years. The main reason is my calm and clear goals, it won't get stuck with the game all day long. In college, I realized that playing games will affect my normal study and work, but I still cannot control myself. I still can't help playing games regularly and play them all day and night, I am still playing games, which is also one of the reasons why I have only played games, left-right hands, and no girlfriend for four years in college ). Now that I work, I have a task every day. when I see the cool people in the project, I have the idea of catching up with them, so every day, I will give myself an extra small task to learn new knowledge. now I have been working for half a year, and I should be familiar with linux I was not familiar, I have a new understanding of unfamiliar JavaScript. now I can say that I am competent in my work (if I am a newbie, a newbie, a winner, an expert, activities, interfaces, backend, and system framework have been developed and optimized. as long as it is a reasonable requirement of product operation, quick support can be provided. Of course, it is true that programmers are really a strange group and often feel that their ideas are the best. Of course, this is self-confidence, but sometimes it is not necessarily a good thing for you to be aggressive during the discussion. so you need to listen to other people's ideas, not only to discover your own shortcomings, but also to establish a good one: "Friendship". I have talked with you a little bit about this experience over the past six months. thank you for your patience.

The following describes how to skillfully use php magic methods. I believe this will be used in most projects.

I already have a good application of this tips in the project, which has brought great convenience to our project. here, I will first sell the selling customs. you may wish to continue to look at it.

In projects, configuration information that can be configured must exist in large quantities, such as the robot opening time period of a game, the opening of payment methods, and the title configuration displayed on the Mall, there is generally no specific rule in these configuration information, and the product operation can be changed at any time according to the actual situation. how can this information be saved, certainly not every type creates a table, this is simply laborious and thankless, you think, maybe a table will save a piece of information, so you have to think about other methods, although there are no rules for this information, they have a feature that there will not be too many, and in general, the array can save all the information to be configured, therefore, using json strings to store information is a good choice. when you need to use json_decode, you can directly use it, next, let's take a look at how to use php magic to implement it.

Here, you first need to understand a magic method _ call () in php, and check the official php documentation to explain this function.

public mixed __call ( string $name , array $arguments )__call() is triggered when invoking inaccessible methods in an object context.

This function is triggered when an inaccessible method (no permission or nonexistent) is called in an object. The $ name parameter of the function is the name of the called function, $ arguments is an array of called function parameters. Let's take a look at the example below:

Class Test {public function _ call ($ name, $ arguments) {echo "you called a method that does not exist: \ r"; echo "function name: {$ name} \ r "; echo" parameter: \ r "; print_r ($ arguments) ;}}$ T = new Test (); $ T-> setrobottime ("12", "18 ");

This function outputs the following results.

You have called a non-existent method: function name: setrobottime parameter: Array ([0] => 12 [1] => 18)

In this way, we can use this feature instead of directly defining functions. Let's take a look at the implementation ideas of the code. some of them are hypothetical, just like database connections. this is not the main idea here.

Class Config {/*** assume that the name of the database table is * config. config, * field: * config_key varchar (50), * config_value text, * primary key (config_key) ** The database connection is $ link *. the insert method is encapsulated as query *. the method for obtaining information is encapsulated as getOne * // The operation to be performed */private static $ keys = array (// 'Call method' => 'key ', 'roboottime' => 'roboottime', 'dailysignin' => 'dailysignin ',); /*** setting method ** @ param string $ config_key configuration item key * @ param string $ config_value configuration item content (generally jso N format) * @ returne boolen true/false whether insertion is successful */private function set ($ config_key, $ config_value) {$ SQL = "insert into config. config (config_key, config_value) values ('{$ config_key}', '{$ config_value}') on duplicate key update config_value = '{$ config_value }'"; return $ link-> query ($ SQL );} /*** method for obtaining the value * @ param $ config_key the key of the configuration to be obtained * @ returne string/false json string/failure */private function get ($ config_key) {$ SQL = "select * from config. config where config_key = '{$ config_key}' "; if ($ ret = $ link-> getOne ($ SQL, MYSQL_ASSOC) {return $ ret;} return false ;} /*** overload magic method ** @ param string $ name the name of the method called * @ param array $ parameter passed during arguments call * @ return mixed returned result */public function _ _ call ($ name, $ arguments) {$ act = substr ($ name, 0, 3); $ func = substr ($ name, 3); if (! In_array ($ func, self: $ keys) {return false;} if ($ act = 'set') {return $ this-> set (self :: [$ func], $ arguments [0]);} elseif ($ act = 'get') {return $ this-> get (self :: [$ func]);} return false ;}}

In this way, we can store multiple pieces of information through a table, which is convenient to call. we only need to extend the information in the Config: $ keys array, this is only for standardization, so that you can clearly know which configurations are stored in this table.

You can store and obtain data in this way.

$ Config = new Config (); $ info = array ("12", "20"); // Set $ config-> setroboottime (json_encode ($ info )); // Get $ config-> getroboottime ();

Note that the configuration information is usually cached in redis and stored in the database to prevent redis from being recovered from the database, this generally refers to the information that is frequently read. in order to reduce interaction with the database, it is directly stored in the cache.

The copyright of this article is owned by the author iforever (luluyrt@163.com), without the author's consent to prohibit any form of Reprint, repost the article must be in the obvious position on the article page to give the author and the original connection, otherwise, you are entitled to pursue legal liability.

Posted @ running Man reading (...) comment (...) edit favorites

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.