DI dependency injection and singleton implementation of phalapi

*文
Release: 2023-03-18 10:10:01
Original
1789 people have browsed it

I believe many people are familiar with the simple interest model and dependency injection. This article mainly explains the DI dependency injection and singleton mode of phalapi. Students who are interested in dependency injection and singleton mode can take a look.

1. Singleton mode

The singleton mode should not be unfamiliar to children who have done object-oriented programming for a long time. Children who are learning PHP should also have heard of it. Here is a brief chat. Let’s talk about what the singleton pattern is, what problems it solves, and how it is implemented in PhalApi.

Singleton Singleton, the so-called singleton means that there is and only one existence, this is the singleton For example, it is not difficult to see its benefits because it uses less resources because there is only one. Everyone knows that to use a class, you must have an instance, which is new. Every time an object is new, an area will be generated in the memory to store the instance. If a lot of new is used to instantiate the same object in one run of the program, it will consume more resources. However, if it is a universal program that uses global variables, it will be inelegant and messy. In this case The singleton mode was born.


The singleton mode is a method that has the best of both worlds. It can be used globally, secondly, there is no need to worry about occupying too many resources, and thirdly, it is very elegant. Let's take a look at how to implement the singleton mode in PhalApi:

//大家看到我们常用的DI方法内部实现的是PhalApi_DI中的静态方法one方法
function DI() {
    return PhalApi_DI::one();
}
Copy after login

Then we look inside the one method


Every time we request it When calling, first verify whether the static variable instance has not been initialized. If it is the first call, it will instantiate the PhalApi_DI class internally and then give a negative value to $instance and then return the static variable of the instance. When we request it next time When this static variable has been instantiated, it will directly skip the instantiation process and return the object directly. That is, the DI method we use in all places of the PhalApi framework is actually an object, and there is only one area in the memory. , the code is as follows:

public static function one(){
    if(self::$instance == NULL){
        self::$instance = new PhalApi_DI();
        self::$instance->onConstruct();
    }
    return self::$instance;
}
Copy after login

In fact, it is not difficult. We only use new to encapsulate the operation of a class into the static method of the class we need new. After making the same judgment as above, we can easily implement a singleton. Mode.


#2. Dependency injection

Dependency injection is also called "inversion of control". If you are familiar with the spring framework of javaweb development, you should have a comparison Deep feelings, I won’t go into details here, just briefly explain the implementation of DI dependency injection in PhalApi so that everyone can understand how to implement this design pattern and the lazy loading mechanism implemented on this basis.


2.1 DI Dependency Injection Implementation

The DI() method commonly used in PhalApi is to use the so-called singleton mode above. Needless to say, we each The first time you use DI() is actually using the PhalApi_DI class, so the key to our dependency injection is in PhalApi_DI


Let’s first talk about one of its implementation methods. Talking about the specific implementation, here is an example:

//配置
DI()->config = new PhalApi_Config_File(API_ROOT . '/Config');
Copy after login

In fact, there is an array internally. It uses config as the key and new PhalApi_Config_File(API_ROOT. '/Config') as the value and then saves it when we The next time you use DI->config->get();, it will take out the new class based on the key value config, so it can be said that the config operation depends on DI(), and it is using DI() ->config is always an instance in use, which can also reduce resource consumption.

Some children are curious why DI()->config will be saved in the array when needed. Take it out. If you are interested in children's shoes, you can Baidu the magic method ser and get

/**大家可以看到这是PhalApi_DI中的魔法方法__set
 * 也就是当使用DI()->config = new PhalApi_Config_File(API_ROOT . '/Config');的时候
 * 获得的name值就是config,获得的value也就是new PhalApi_Config_File(API_ROOT . '/Config');
 */get同理,在内部实现都是调用了内部get和set方法
public function __set($name, $value){
    $this->set($name, $value);
}
public function __get($name){
    return $this->get($name, NULL);
}
Copy after login

After reading it, do you think it is very simple? You can also use this flexible magic when designing your own classes in the future. Method implementation.


2.2 Lazy loading

The DI() method in PhalApi also provides lazy loading. Lazy loading literally means that when the class does not It will not be loaded when it is used. This operation is also to avoid wasting unnecessary resources. When we are not using it, we will never instantiate it. Only when you use it will we new the class and then instantiate it. Using, let’s take a look at how to implement it.

//当我们执行以下语句的时候,在依赖注入的时候存的是value值是字符串的test
DI()->test = 'test';
//使用DI()->test->test();的时候会使用到PhalApi中的get方法,在get方法中有一段代码
$this->data[$key] = $this->initService($this->data[$key]);
//在initService方法内部验证了value是字符串就实例化了再返回
if($config instanceOf Closure){
    $rs = $config();
}elseif(is_string($config) && class_exists($config)){
    $rs = new $config();
    if(is_callable(array($rs, 'onInitialize'))){
        call_user_func(array($rs, 'onInitialize'));
    }
}else{
    $rs = $config;
}
Copy after login

Related recommendations:

##How to achieve database read-write separation with phalapi

phalapi-cache usage and redis expansion

PhalApi (π framework)

The above is the detailed content of DI dependency injection and singleton implementation of phalapi. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!