


Best Practices Series - Talking about PHP components, frameworks, and Composer
1. What is a component A component is a set of packaged codes, a series of related classes, interfaces and Traits that are used to help us solve a specific problem in PHP applications. For example, if your PHP application needs to send and receive HTTP requests, it can be implemented using ready-made components such as guzzle/guzzle. We use components not to reimplement functions that have already been implemented, but to spend more time on achieving the long-term goals of the project.
Excellent PHP components have the following characteristics:
When we choose a framework, we have to invest a lot in the tools of this framework. The framework usually provides a large number of tools, but when it does not provide a tool we need, the pain is passed on to us. We have to find and integrate it ourselves. Defined PHP library. Integrating third-party code into a framework can be difficult because the third-party code and the framework may not use the same interfaces.
When choosing a framework, we focus on the future of the framework, but who can guarantee that a certain framework will always be the best tool to complete a certain job? Large projects that have been around for many years must perform well and make adjustments all the time. If you choose the wrong PHP framework, you may not be able to do this. Older PHP frameworks may be slow or outdated due to lack of community support. These older frameworks are often written using procedural code instead of modern object-oriented code and some of the new features of PHP. In short, when deciding whether to use a PHP framework, There are many things to consider.
Fortunately, Laravel performed well in these concerns, so it can stand out among the many PHP frameworks. In a sense, Laravel is also a framework for component development (the core component is its own Illuminate library. It relies heavily on third-party components). Compared with Symfony, it is easier to get started, so it has both scalability and ease of use. However, Laravel also has some shortcomings. For example, Laravel's own components cannot be easily decoupled and used outside the Laravel framework (but I believe this situation will improve, for example, its database and queue components can be decoupled). Taken together, Laravel is still an excellent framework that can help us quickly create powerful applications. So should we use components or frameworks? The answer is, use the right tool for the right thing. If you can implement small projects quickly with some PHP components, use components. If you have multiple team members working on large projects, you can benefit from the agreed guidelines and structure provided by the framework. , then use a framework (if you are confused about which framework to use, then choose Laravel, it will not let you down). Using a framework can guide and accelerate the development of the project. PS: This sentence also applies to language disputes. Use the right language to do the right thing, and you will be fine.3. Use components Packagist We look for PHP components in Packagist. This website is used to collect PHP components. The best PHP components can be found in Packagist. For example, if we want to use an http component to send and receive HTTP messages, search for http in the search box, and the first result we get is Guzzle, so use it.
Composer Packagist is a community for finding PHP components, and Composer is a tool for installing PHP components. Composer is a dependency manager for PHP. It runs on the command line. You tell Composer which components you need, and Composer will download and automatically load these components into your project. It's that simple.
Composer and Packagist work closely together. If you tell Composer that you want to use the guzzlehttp/guzzle component, Composer will get the guzzlehttp/guzzle component from Packagist, find the warehouse address of this component, determine which version to use, and also find out this component dependencies, and then download the guzzlehttp/guzzle component and its dependencies into your project.
In addition, Composer will automatically generate autoloaders that comply with PSR standards for all PHP components in the project, effectively abstracting dependency management and automatic loading. Therefore, for the PHP community, Composer is the most important additional tool. First, it is not an exaggeration to think about the painful days when we had to use include, require, and spl_autoload_register to manually implement automatic loading.
About the installation and use of Composer, I won’t go into details here. Please refer to the Composer Chinese website.
4. Sample projectBelow we use a sample project to demonstrate how to use Composer and components to develop a PHP application. The role of this application is to scan the URL in a CSV file and find the dead chain. If the returned HTTP status code is greater than or equal to 400, the dead link is sent to the standard output. This is a command line application. After development, we will execute this script, pass in the path of the csv file, and display the dead link list in the standard output. Install components Let’s take a look at which tasks can be solved using existing PHP components: we need a component that can iterate over the data of the csv file, in addition to sending HTTP requests to each URL in the csv file, so we also need a A component that can send HTTP requests and inspect HTTP responses. After browsing Packagist, we found two components: guzzlehttp/guzzle and league/csv. The former is used to process HTTP messages, and the latter is used to process CSV data. Next we run the following command at the top level of the project: The composer.lock file will list all the PHP components used by the project, as well as the specific version numbers of the components. This actually locks the project so that the project can only use specific versions of PHP components. The advantage of this is that composer will download the specific version listed in this file, regardless of the latest version available in Packagist. You should put the composer.lock file into version control so that team members are using the same PHP version as you. , if the PHP component versions used by local development and the server are the same, bugs caused by different component versions can be minimized.
If you really want to download the latest version of the component and update composer.lock, you can use the composer update command.
Auto loading Next we write the application code, create a scan.php file in the root directory, and then use require at the top of the file to import the autoloader created by Composer:
The autoloader created by Composer is actually a file named autoload.php, which is saved in the vendor directory. When Composer downloads each PHP component, it will check the composer.json file of each component to determine how to load the component. , after getting this information, Composer will create an autoloader locally for the component that conforms to the PSR standard. This way we can instantiate any PHP component in the project and these components will be automatically loaded on demand.
Write code Below we formally use Guzzle and CSV components to write the scan.php code:
Next we add some URLs to urls.csv, one per line, and at least one is a dead link:
Then open the terminal and execute the scan.php script:
We passed in two parameters, the first is the path to the script file scan.php, and the other is the path to the CSV file. The output is as follows:
Due to restrictions on uploading attachments and text, sometimes some pictures and text may not be displayed. For details, please see: http://mp.weixin.qq.com/s?__biz=MzI5ODI3NzY2MA==&mid=100000610&idx=3&sn=e4974922c197cb2e227d7352376ab0c3#rd Everyone is welcome to communicate. Scan the QR code below to get more and more beautiful articles! (Scan the QR code to follow for unexpected surprises!!) ![]() Follow our WeChat subscription account (uniguytech100) and service account (uniguytech) to get more and more exquisite articles! You are also welcome to join [Everyone Technology Network Discussion QQ Group], group number: 256175955, please note your personal introduction! Let’s talk about it together! |

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Alipay PHP...

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.
