Talk about PHP Components, Frameworks, Composer

1. 1.What is a component

A component is a set of packaged code. It is a series of related classes, interfaces, and Trait that help us solve a specific problem in a PHP application. For example, your PHP application needs to send and receive HTTP requests. You can use off-the-shelf components such as guzzle/guzzle. We don’t use components to re-implement what we have already achieved, but to spend more time on the long-term goals of the project.

Excellent PHP components have the following characteristics:

  • Single role: focus on solving a problem, and use a simple interface to encapsulate functions
  • Small: Small and compact, containing only the minimum code needed to solve a problem
  • Cooperation: PHP components can work well together to achieve large projects
  • Good testing: Provides testing itself, and has sufficient test coverage
  • Document perfection: There should be complete documentation to make it easy for developers to install, understand and use

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 lot of tools, but when we do n’t provide one of the tools we need, the pain is passed on to us. We have to find and integrate custom PHP library. Integrating third-party code into the framework is difficult because third-party code and frameworks may not use the same interface.
When choosing a framework, we look at the future of the framework, but who can guarantee that a framework is always the best tool to accomplish a certain job? Large projects that have existed for many years must have good performance, and they must always be adjusted. 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 usually written using procedural code instead of new-style object-oriented code and some new features of PHP. In short, when deciding whether to use the PHP framework, There are many things to consider.

Fortunately, Laravel has performed well in 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, and a large number of functional implementations Depends on third-party components), compared to 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, such as its database and queue components can be decoupled). Overall, Laravel is still an excellent framework that can help us quickly create powerful applications.

Should we use components or frameworks? The answer is to use the right tools to do the right thing. If you can quickly implement small projects through some PHP components, then use components. If you have multiple team members developing large projects, you can benefit from the conventions and structure provided by the framework. Then, use a framework (if you are struggling with what framework to use, then choose Laravel, it will not let you down), use a framework to guide and accelerate the development of the project.

3. Using components


We look for PHP components in Packagist. This site is used to collect PHP components. The best PHP components can be found in Packagist.


For example, we want to use an http component to send and receive HTTP messages, and search for http in the search box. The first result we get is Guzzle. Use it.


Packagist is a community for finding PHP components, Composer is a tool for installing PHP components. Composer is a PHP dependency manager. It runs on the command line. You tell Composer which components it needs. Composer will download and automatically load these components into your project. It’s that simple.

Composer and Packagist close cooperation, if you want to use to tell Composer guzzlehttp/guzzle components, Composer will get from Packagist the guzzlehttp/guzzle assembly, warehouse find address this component to determine which version to use, but also to find out the dependence of this component, then the guzzlehttp/guzzle component and its Dependencies are downloaded into your project.

In addition, Composer will automatically generate PSR-compliant autoloaders for all PHP components in the project, effectively abstracting dependency management and autoloading. Therefore, for the PHP community, Composer is the most important additional tool. It is not too much to think about the painful days when we had to manually implement autoloading using include, require, and spl_autoload_register.

Regarding the installation and use of Composer, I won’t go into details here.

4. Sample project

Below we use an example project to demonstrate how to use Composer and components to develop a PHP application. The purpose of this application is to scan the URL in a CSV file to find the dead link. The application will make an HTTP request to each URL. If it returns The HTTP status code is greater than or equal to 400, and this dead link is sent to 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 chain list in the standard output.

Install components

Before you start, let’s see what tasks can be solved using existing PHP components: we need a component that can iteratively process the data of the csv file, and also send an HTTP request to each URL in the csv file, so we also need one that can send A component that makes HTTP requests and checks HTTP responses.

After browsing Packagist, we find guzzlehttp/guzzle, and league/csv he two components, the former for processing HTTP messages, which is used for processing CSV data. Below we run the following command at the top level of the project:

composer require guzzlehttp/guzzle
composer require league/csv

Composer will install dependencies to the root directory. vendor After the installation is complete, it will generate composer.json and composer.lock files in the root directory :

This is image title

composer.lock The file will list all PHP components used by the project, as well as the specific version number of the component. This actually locks the project so that the project can only use a specific version 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 the team members use the same PHP version as you. Development and server use the same version of PHP components, you can minimize bugs caused by different component versions.
If you really want to download the latest version of the component and update it composer.lock, you can use the composer update command.


Next we write the application code, create a scan.php file in the root directory , and then use require the autoloader created by importing Composer at the top of the file :

The autoloader created by Composer is actually a file named autoload.php, which is stored in the vendor directory. When Composer downloads each PHP component, it checks the composer.json file of each component to determine how to load the component and get this information Later, Composer will create a PSR-compliant autoloader for the component locally. This way we can instantiate any PHP components in the project, which are automatically loaded on demand.
Write code
Below we formally write scan.php code using Guzzle and CSV components:
//Guzzle Http Client
$client = new GuzzleHttp\Client();
//Open and iteratively process CSV
$csv = League\Csv\Reader::createFromPath($argv[1]);
foreach ($csv as $csvRow) {
try {
//Send HTTP GET request
$httpResponse = $client->get($csvRow[0]);
    //Check the status code of the HTTP response
    if($httpResponse->getStatusCode() >= 400) {
        throw new Exception();
} catch (Exception $e) {
        //Send dead chain to standard output
        echo $csvRow[0] . PHP_EOL;

Below we add some URLs in urls.csv, one per line, and at least one is a dead link:
Then open a terminal and execute the scan.php script:
php scan.php urls.csv
We passed 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:
In the next section we will explore private PHP components and how to create your own PHP components and upload them to Packagist.

#php #component #framework #composer

Talk about PHP Components, Frameworks, Composer
3.25 GEEK