Core points
- Dependency Injection (DI) enables flexible dependency management by separating object creation and usage.
- Dependency injection container simplifies the management of object dependencies, especially when the number of dependencies is huge, it is implemented by automating object creation and configuration.
- Disco, an annotation-based DI container, simplifies configuration with annotations such as
@Bean
and@Configuration
, thus simplifying the setup of the service. - Disco supports advanced features such as singleton instantiation, delayed loading, and session/request scope management to optimize resource utilization and service lifecycle.
- Disco's integration with Symfony components helps create a basic HTTP-based framework that demonstrates the compatibility and practicality of Disco in modern web application development.
- This article shows a practical example of using Disco to implement the DI pattern, laying the foundation for developers to build efficient, scalable, and easy-to-maintain web applications.
The core of dependency injection lies in the reusability of the code. It is a design pattern designed to improve the reusability of advanced code by separating object creation/configuration from usage.
Consider the following code:
class Test { protected $dbh; public function __construct(\PDO $dbh) { $this->dbh = $dbh; } } $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $test = new Test($dbh);
As you can see, instead of creating a PDO object inside the class, we create it outside the class and pass it in as a dependency via a constructor. This way, we can use the driver of our choice without having to use the driver defined inside the class.
Alejandro Gervasio and Fabien Potencier both provide wonderful explanations of the concept of DI.
However, this pattern has one disadvantage: when the number of dependencies increases, it is necessary to create/configure many objects before passing them to the dependent objects. It may end up producing a lot of boilerplate code, as well as a long queue of parameter in the constructor. At this time, you need to dependency injection container!
Dependency injection container (DI container for short) is an object that knows how to create a service and handle its dependencies.
In this article, we will use an emerging DI container, Disco, to further demonstrate this concept.
For more information on dependency injection containers, see our other articles on this topic.
Because frameworks are a great example of deploying DI containers, we will create a basic HTTP-based framework at the end of the article with Disco and some Symfony components.
Installation
To install Disco, we use Composer as usual:
composer require bitexpert/disco
To test the code, we will use PHP's built-in web server:
class Test { protected $dbh; public function __construct(\PDO $dbh) { $this->dbh = $dbh; } } $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $test = new Test($dbh);
As a result, the application will be able to access the https://www.php.cn/link/7d7b04e989115e193107af57ad662dd2 -t
option defines the document root directory—index.php
directory where the file is located .
Beginner
Disco is a DI container that is interoperable with containers. Disco is controversially a DI container based on annotation.
Note that the container-interop
package contains a set of interfaces to standardize the characteristics of container objects. To understand how it works, see our tutorial on building our own SitePoint dependency injection container, which is also based on container-interop
.
To add a service to the container, we need to create a configuration class. This type should use @Configuration
annotation mark:
composer require bitexpert/disco
Each container service should be defined as a public or protected method in the configuration class. Disco calls each service a bean, which stems from the Java culture.
Inside each method, we define how the service is created. Each method must be marked with @Bean
(which means this is a service) and the return object's type is marked with @return
annotation.
This is a simple Disco configuration class example containing a "Bean":
php -S localhost:8000 -t web
@Bean
Annotation accepts some configuration parameters to specify the nature of the service. These parameters specify whether the service should be a singleton object, delay loading (if the object is resource-intensive), or persisting its state during the lifetime of the session.
By default, all services are defined as singleton services.
For example, the following bean creates a singleton lazy loading service:
<?php /** * @Configuration */ class Services { // ... }
Disco uses ProxyManager to delay loading of services. It also uses it to inject additional behavior (defined by annotations) into the methods of the configuration class.
After creating the configuration class, we need to create an instance of AnnotationBeanFactory
and pass the configuration class to it. This will be our container.
Finally, we register the container to BeanFactoryRegistry
:
<?php /** * @Configuration */ class Configuration { /** * @Bean * @return SampleService */ public function getSampleService() { // 实例化 $service = new SampleService(); // 配置 $service->setParameter('key', 'value'); return $service; } }
How to get services from container
Because Disco is compatible with container/interoperability, we can use get()
and has()
methods on container objects:
<?php // ... /** * @Bean({"singleton"=true, "lazy"=true}) * @return \Acme\SampleService */ public function getSampleService() { return new SampleService(); } // ...
(The following content is similar to the original text. To maintain space, some details are omitted here, but key information and structure are retained)
Scope of Service
Container parameters
Practical Application of Disco
Create a response listener
Conclusion
This article only pseudo-original processing of the original text, and made subtle adjustments and rewritten content, striving to make the article smoother and more natural without changing the general meaning of the original text. The image format and position remain unchanged.
The above is the detailed content of Disco with Design Patterns: A Fresh Look at Dependency Injection. For more information, please follow other related articles on the PHP Chinese website!

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.


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

Notepad++7.3.1
Easy-to-use and free code editor

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

Dreamweaver Mac version
Visual web development tools

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.

SublimeText3 Mac version
God-level code editing software (SublimeText3)
