yii2 Essay (7) Dependency Injection - (4) Service Locator
Service locator locator is a solution to dependency injection. It includes dependency injection. After dependency injection is solved, if the service user and service provider are not the same person, then the user must understand the method of providing the service. Parameters are required to ensure the correctness of dependencies, which couples users and providers. The service locator decouples this part. The service provider registers the service in the ServiceLocator (and registers the dependencies at the same time), and only tells the service to use or the names or aliases of those services, then it is good for both service providers and users. Users only need to know what services the provider provides, but do not need to know what they depend on, and service providers do not need to "use them randomly" for users. "Troubled by bugs caused by service.
So how does yii2 use ServiceLocator? In fact, it is very simple as follows
//魔术方法, public function __get($name){ //得到某个注册的方法 if ($this->has($name)) { return $this->get($name); } else { return parent::__get($name); } } //魔术方法查看某个服务是否存在,源码略 public function __isset($name){} //__isset()中调用,查看某个服务是否存在,源码略 public function has($id, $checkInstance = false){} //得到某个服务 public function get($id, $throwException = true) { if (isset($this->_components[$id])) {//如果是已经处理的服务,就直接返回 return $this->_components[$id]; } if (isset($this->_definitions[$id])) {//如定义了该服务 $definition = $this->_definitions[$id];//得到服务的定义 //如果服务是一个闭包,则把闭包注册到已经实例化的服务中,并且返回闭包 if (is_object($definition) && !$definition instanceof Closure) { return $this->_components[$id] = $definition; } else {//其他的情况下通过依赖注入生成对象,并且注册为已处理,返回对象 return $this->_components[$id] = Yii::createObject($definition); } } elseif ($throwException) {//如果抛出异常,则抛出异常 throw new InvalidConfigException("Unknown component ID: $id"); } else {//其他返回null return null; } } //注册一个服务 public function set($id, $definition) { if ($definition === null) {//如果该服务的定义为null,则删除已经实例化的服务,返回空,用于注销已经实例化的并且保存过的服务的定义 unset($this->_components[$id], $this->_definitions[$id]); return; } //清空已经实例化的服务 unset($this->_components[$id]); //如果该服务的定义为一个对象,并且是一个可调用的结构 if (is_object($definition) || is_callable($definition, true)) { // an object, a class name, or a PHP callable $this->_definitions[$id] = $definition; } elseif (is_array($definition)) {//如果该服务是一个配置数组 // a configuration array if (isset($definition['class'])) {//如果有class键值,则直接注册为一个服务的定义 $this->_definitions[$id] = $definition; } else {//是配置数组,但是没有指定class,则抛出异常 throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element."); } } else {//什么都不是,抛出异常,非法注册服务 throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition)); } } //清空已经实例化过的服务和定义,代码略 public function clear($id){} //得到已经实例化后的服务,或者得到可用的服务配置 public function getComponents($returnDefinitions = true){} //注册所有的服务,这里的$components,就是你在config里写的 $config['components']值 public function setComponents($components){}
So when did ServiceLocator get involved? Let's continue to open our index.php, pay attention to the following sentence
(new yii\web\Application($config))->run();
Let's check Application
class Application extends \yii\base\Application //继续追踪 \yii\base\Application abstract class Application extends Module //继续追踪 Module class Module extends ServiceLocatorHa, finally found it! ! ! Our application is actually a service locator. The components we configure in the configuration file are all services registered by the service locator of the application. Now you know why the function is called setComponents. If you don’t understand, continue reading.
yii uses the set[typename] function to ensure the writability of attributes. Yii::configure($this, $config); is used in the constructor of the base class yii\base\Object; this will Call the setComponents function to register the service.
Okay, we have contacted each other before and after. That’s all for the dependency injection and service locator used by yii2.
The above is the yii2 essay (7) Dependency Injection - (4) The content of the service locator. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
