Home Backend Development PHP Tutorial Clever overloading of the magic method __call()

Clever overloading of the magic method __call()

Aug 08, 2016 am 09:31 AM
config function key

I have been working for half a year, and I feel that I have learned more in this half year than in four years of college. The main reason is that my mind has calmed down, my goals are clear, and I will not be entangled with games all day long. When I was in college, I actually realized that playing games would affect my normal study and work, but I couldn't control myself. I still couldn't help but play often, day and night (I was originally a sultry guy, and I still stayed at home playing games. , this is also one of the reasons why I only had games, left and right hands, and no girlfriends during the four years of college). Now that I am working, I have tasks every day. When I see the talented people next to me working on the project like a duck to water, I have the idea of ​​catching up with them, so I give myself an extra small task every day to learn new knowledge. I have been working for half a year now. Now I can use Linux which I was not familiar with before. I also have a new understanding of JS which I am not familiar with. It can be said that I am competent at the job now (if divided into novice, advanced novice, competent and proficient) , experts), have developed activities, interfaces, and backends, and have also optimized and improved the system framework. As long as there are reasonable needs raised by product operations, they can be quickly supported. Of course, I really feel one thing: Programmers are really a strange group. Most of the time, they always think that their own ideas are the best. Of course, this is considered self-confidence, but sometimes your aggressiveness during discussions is not necessarily a good thing, so you should listen to other people's ideas. Not only can you discover your own shortcomings, but you can also build a good "friendship". I’ve been telling you so much about my feelings over the past six months, thank you for sticking with me and reading it^_^.

Let’s step into the real question and talk about how to skillfully use the magic method of PHP. I believe this will be used in most projects.

First of all, I would like to explain that this little trick has been used very well in my project, and it has brought great convenience to our project. I will give you some details here, you may wish to continue reading.

In the project, there must be a large amount of configuration information that can be configured, such as the robot opening time period of a game, whether the payment method is enabled, the configuration of the title display in the mall, etc. One characteristic of these configuration information is that there is no specific Rules, and product operations can be modified at any time according to the actual situation. How to save this information? It is definitely not possible to build a table for each type. Doing so is simply thankless. If you think about it, maybe one table can A piece of information is saved, so I have to think of other methods. Although there are no rules for this information, one of their characteristics is that there will not be too much, and generally an array can save all the information that needs to be configured, so json characters are used String storage information is a good choice. When you need to use it, just take out the json_decode and you can use it directly. Let’s take a look at how to cleverly use PHP’s magic method to achieve it.

Here you first need to understand __call(), a magic method of PHP. Check the official PHP documentation, which explains this function like this

<span>public</span> <span>mixed</span> __call ( <span>string</span> <span>$name</span> , <span>array</span> <span>$arguments</span><span> )

__call() is triggered when invoking inaccessible methods in an </span><span>object</span> context.
Copy after login

It means that this function will be triggered when an inaccessible method (no permission, non-existence) is called in an object. The parameter $name of the function is the name of the called function, and $arguments is the parameter array of the called function. Take a look at this example:

<span>class</span><span> Test
{
    </span><span>public</span> <span>function</span> __call(<span>$name</span>, <span>$arguments</span><span>)
    {
        </span><span>echo</span> "你调用了一个不存在的方法:\r"<span>;
        </span><span>echo</span> "函数名:{<span>$name</span>}\r"<span>;
        </span><span>echo</span> "参数: \r"<span>;
        </span><span>print_r</span>(<span>$arguments</span><span>);
    }
}

</span><span>$T</span> = <span>new</span><span> Test();
</span><span>$T</span>->setrobottime("12", "18");
Copy after login

This function will output the following results

<span>你调用了一个不存在的方法:
函数名:setrobottime
参数: 
Array
(
    [</span>0] => 12<span>
    [</span>1] => 18<span>
)</span>
Copy after login

In this way, we can not define the function directly, but use this feature to do something. Let’s take a look at the implementation ideas of the code, mainly the ideas, some of which I have made assumptions about, such as database connections, which I won’t focus on here.

<span>class</span><span> Config
{
    </span><span>/*</span><span>*
     * 这里假定下数据库表名为
     * config.config,
     * 字段为:
     * config_key varchar(50),
     * config_value text,
     * primary key(config_key)
     *
     * 数据库连接为$link
     * 插入方法封装为query
     * 获取一条信息方法封装为getOne
     </span><span>*/</span>
    <span>/*</span><span>*
     * 要进行的操作
     </span><span>*/</span>
    <span>private</span> <span>static</span> <span>$keys</span> = <span>array</span><span>(
        </span><span>//</span><span>'调用方法' => 'key',</span>
        'roboottime'    => 'ROBOOTTIME',
        'dailysignin'   => 'DAILYSIGNIN',<span>
    );

    </span><span>/*</span><span>*
     * 设置方法
     * @param string $config_key 配置项key
     * @param string $config_value 配置型内容(一般为json格式)
     * @returne boolen true/false 插入是否成功
     </span><span>*/</span>
    <span>private</span> <span>function</span> set(<span>$config_key</span>, <span>$config_value</span><span>){
        </span><span>$sql</span> = "insert into config.config (config_key,config_value) values ('{<span>$config_key</span>}','{<span>$config_value</span>}') on duplicate key update config_value='{<span>$config_value</span>}'"<span>;
        </span><span>return</span> <span>$link</span>->query(<span>$sql</span><span>);
    }

    </span><span>/*</span><span>*
     * 获取值的方法
     * @param $config_key 要获取的配置的key
     * @returne string/false json字符串/失败
     </span><span>*/</span>
    <span>private</span> <span>function</span> get(<span>$config_key</span><span>)
    {
        </span><span>$sql</span> = "select * from config.config where config_key='{<span>$config_key</span>}'"<span>;
        </span><span>if</span>(<span>$ret</span> = <span>$link</span>->getOne(<span>$sql</span>,<span> MYSQL_ASSOC)){
            </span><span>return</span> <span>$ret</span><span>;
        }
        </span><span>return</span> <span>false</span><span>;
    }

    </span><span>/*</span><span>*
     * 重载魔术方法
     * @param string $name 被调用的方法名
     * @param array $arguments 调用时传递的参数
     * @return mixed 返回结果
     </span><span>*/</span>
    <span>public</span> <span>function</span> __call(<span>$name</span>, <span>$arguments</span><span>)
    {
        </span><span>$act</span>    = <span>substr</span>(<span>$name</span>, 0, 3<span>);
        </span><span>$func</span>   = <span>substr</span>(<span>$name</span>, 3<span>);
        </span><span>if</span>(!<span>in_array</span>(<span>$func</span>, self::<span>$keys</span><span>)){
            </span><span>return</span> <span>false</span><span>;
        }
        </span><span>if</span>(<span>$act</span> == 'set'<span>)
        {
            </span><span>return</span> <span>$this</span>->set(self::[<span>$func</span>], <span>$arguments</span>[0<span>]);
        }
        </span><span>elseif</span>(<span>$act</span> == 'get'<span>)
        {
            </span><span>return</span> <span>$this</span>->get(self::[<span>$func</span><span>]);
        }
        </span><span>return</span> <span>false</span><span>;
    }
}</span>
Copy after login

In this way, we can store multiple information through one table, and it is very convenient when calling. We only need to expand the information in the Config::$keys array. This is just for standardization and clarity. Know which configurations are stored in this table.

You can store and retrieve it like this when using it

<span>$config</span> = <span>new</span><span> Config();

</span><span>$info</span> = <span>array</span>("12","20"<span>);

</span><span>//</span><span>设置</span>
<span>$config</span>->setroboottime(json_encode(<span>$info</span><span>));

</span><span>//</span><span>获取</span>
<span>$config</span>->getroboottime();
Copy after login

Another point to note here is that these configuration information will generally be cached in redis and placed in the database just to prevent recovery from the database after redis hangs. This generally refers to information that is frequently read. In order to reduce the interaction with the db, place it directly in the cache.

 The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author's consent. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved. .

posted @ 2015-01-10 12:23 Running Man Read (...) Comment (...) Edit Collection

Refresh comments Refresh page Return to top

Blog Park Homepage Bowen News Flash Programmer Recruitment Knowledge Base

公告

Copyright ©2015 奔跑的Man

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to fix error 0xC00CE556 returned by the .NET parser How to fix error 0xC00CE556 returned by the .NET parser Apr 25, 2023 am 08:34 AM

While installing a new version of an application, Windows may display this error message "An error occurred while parsing C:\\Windows\Microsoft.Net\Framework\v2.0.50727\Config\machine.configParser returned error 0xC00CE556". This problem also occurs when your system boots. No matter what situation you encounter this problem, .NETFramework is the real culprit behind the scenes. There are some very simple fixes you can use to stop this error code from appearing again. Fix 1 – Replace corrupted files You can easily replace corrupted ma from the original directory

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

What does the identity attribute in SQL mean? What does the identity attribute in SQL mean? Feb 19, 2024 am 11:24 AM

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

How SpringBoot monitors redis Key change events How SpringBoot monitors redis Key change events May 26, 2023 pm 01:55 PM

1. Function Overview Keyspace notification allows clients to receive events that modify Rediskey changes in some way by subscribing to channels or patterns. All commands that modify key keys. All keys that received the LPUSHkeyvalue[value…] command. All expired keys in the db database. Events are distributed through Redis's subscription and publishing functions (pub/sub), so all clients that support subscription and publishing functions can directly use the keyspace notification function without any modifications. Because the current subscription and publishing functions of Redis adopt a fireandforget strategy, if your program

How to solve the problem of batch deletion of key values ​​in redis How to solve the problem of batch deletion of key values ​​in redis May 31, 2023 am 08:59 AM

Problems encountered: During the development process, you will encounter keys that need to be deleted in batches according to certain rules, such as login_logID (ID is a variable). Now you need to delete data such as "login_log*", but redis itself only has batch query. Command keys for class key values, but there is no command for batch deletion of a certain class. Solution: Query first, then delete, use xargs to pass parameters (xargs can convert pipe or standard input (stdin) data into command line parameters), execute the query statement first, and then remove the queried key value and the original del parameters. delete. redis-cliKEYSkey* (search condition)|xargsr

How to use ThinkPHP\Config for configuration management in php? How to use ThinkPHP\Config for configuration management in php? May 31, 2023 pm 02:31 PM

With the continuous development of the PHP language, ThinkPHP, which is widely used in the PHP back-end framework, is also constantly improving. As business scenarios become increasingly complex, the demand for configuration management in ThinkPHP is also increasing. In this context, ThinkPHP provides rich configuration management functions. Today we will introduce how to implement configuration management through ThinkPHPConfig. 1. Introduction to ThinkPHPConfig ThinkPHPConfig is Thin

Unpatchable Yubico two-factor authentication key vulnerability breaks the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices Unpatchable Yubico two-factor authentication key vulnerability breaks the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices Sep 04, 2024 pm 06:32 PM

An unpatchable Yubico two-factor authentication key vulnerability has broken the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices. The Feitian A22 JavaCard and other devices using Infineon SLB96xx series TPMs are also vulnerable.All

How does php use CodeIgniter\Config for configuration management? How does php use CodeIgniter\Config for configuration management? Jun 02, 2023 pm 06:01 PM

1. Introduction to CodeIgniter CodeIgniter is a lightweight and comprehensive PHP development framework designed to provide web developers with fast and powerful tools to build web applications. It is an open source framework that uses the MVC architecture pattern to achieve rapid development and basic functions, while supporting a variety of databases. 2. Introduction to the Config library The Config library is a component in the CodeIgniter framework and is used to configure and manage code. The Config library contains many

See all articles