亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development PHP Tutorial Best Practices Series - Talking about PHP components, frameworks, and Composer

Best Practices Series - Talking about PHP components, frameworks, and Composer

Jul 25, 2016 am 08:43 AM


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:
  • Single function: focus on solving one problem, and use simple interfaces to encapsulate functions;
  • Small: small and exquisite, containing only the minimum code required to solve a certain problem ;
  • Cooperation: PHP components can cooperate well and be combined to realize large-scale projects;
  • Good testing: it provides testing itself and has sufficient test coverage;
  • Perfect documentation: complete documentation should be provided , allowing developers to easily install, understand and use it.


2. Component vs Framework
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 project
Below 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:


Composer will install the dependencies into the vendor directory of the root directory. After the installation is complete, composer.json and composer.lock files will be generated in the root directory:


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!!)
Best Practices Series - Talking about PHP components, frameworks, and Composer
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!


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

See all articles