Home>Article>Backend Development> A brief discussion of PHP components, frameworks and Composer

A brief discussion of PHP components, frameworks and Composer

little bottle
little bottle forward
2019-04-23 09:18:38 3551browse

This article mainly introduces PHP components, frameworks and Composer, which has certain learning value. Interested friends can learn about it.

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 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, only Contains the minimum code required to solve a problem
  • Cooperation: PHP components can cooperate well with each other and are combined to implement large projects
  • Good testing: It provides testing itself, and there are sufficient tests Coverage
  • Complete documentation: Complete documentation should be provided to allow developers to easily install, understand and use

Components vs frameworks

When we choose a framework, It takes a lot to invest in the tools of this framework. The framework usually provides a lot of tools, but when it does not provide a tool we need, the pain is passed on to us, and we have to find and integrate a custom 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 old 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 has performed well in terms of these concerns, so it can stand out among many PHP frameworks. In a sense, Laravel is also a component-based development framework (the core component is its own Illuminate library , the function implementation 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.

Using 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.

A brief discussion of PHP components, frameworks and Composer

For example, if we want to use an http component to send and receive HTTP messages, search 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. If you tell Composer that you want to use theguzzlehttp/guzzlecomponent, Composer will get theguzzlehttp/guzzlecomponent from Packagist and find this component. The warehouse address, determine which version to use, find out the dependencies of this component, and then download theguzzlehttp/guzzlecomponent 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, Composer is the most important to the PHP community. There is no such thing as additional tools. 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.

Regarding the installation and use of Composer, I will not go into details here. Please refer to the Composer Chinese website.

Sample Project

Below we use a sample project to demonstrate how to use Composer and components to develop a PHP application. The function of this application is to scan the URL in a CSV file to find dead links. The application An HTTP request will be sent to each URL. If the returned HTTP status code is greater than or equal to 400, the dead link will be 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.

Installing components

Before we begin, let’s take a look at which tasks can be solved using existing PHP components: we need a component that can iteratively process the data of the csv file, and also add data to the csv file. Each URL sends an HTTP request, so you also need a component that can send HTTP requests and check the HTTP response.

After browsing Packagist, we found two components:guzzlehttp/guzzleandleague/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 require guzzlehttp/guzzle composer require league/csv

Composer will install the dependencies to thevendordirectory in the root directory. After the installation is completed,composer will be generated in the root directory. .jsonandcomposer.lockfiles:

A brief discussion of PHP components, frameworks and Composer

##composer.lockfile will list all the files used by the project PHP components, as well as the specific version numbers of the components, actually lock 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 thecomposer.lockfile into version control so that team members can use it. The PHP version is the same as yours. If the PHP component versions used by local development and 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 thecomposer updatecommand.

Automatic loading

Next we write the application code, create a

scan.phpfile in the root directory, and then userequire# at the top of the file ##Import the autoloader created by Composer:

require 'vendor/autoload.php';
The autoloader created by Composer is actually a file named

autoload.php

, which is saved in thevendordirectory When Composer downloads each PHP component, it will check thecomposer.jsonfile of each component to determine how to load the component. After obtaining this information, Composer will create a local PSR standard for the component. Autoloader. This way we can instantiate any PHP component in the project and these components are automatically loaded on demand.Writing code

Below we formally use Guzzle and CSV components to write

scan.php

code:

//使用composer自动加载器 require 'vendor/autoload.php'; //实例Guzzle Http客户端 $client = new GuzzleHttp\Client(); //打开并迭代处理CSV $csv = League\Csv\Reader::createFromPath($argv[1]); foreach ($csv as $csvRow) { try { //发送HTTP GET请求 $httpResponse = $client->get($csvRow[0]); //检查HTTP响应的状态码 if($httpResponse->getStatusCode() >= 400) { throw new Exception(); } } catch (Exception $e) { //把死链发给标准输出 echo $csvRow[0] . PHP_EOL; } }
Below we use

urls.csv

Add some URLs, one per line, and at least one is a dead link:

A brief discussion of PHP components, frameworks and ComposerThen open the terminal and execute the

scan.php

script:

php scan.php urls.csv
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:

A brief discussion of PHP components, frameworks and ComposerRelated tutorials:

PHP video tutorial

The above is the detailed content of A brief discussion of PHP components, frameworks and Composer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete