Best Practice Series (i)--ramble about PHP components, frameworks, Composer

Source: Internet
Author: User
Tags autoload autoloader

1. What is a component

A component is a packaged set of code, 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, which can be implemented using ready-made components such as guzzle/guzzle. Instead of using components to re-implement the functionality that has been implemented, we spend more time on the long-term goal of achieving the project.

Excellent PHP components have the following features:

    • Single function: Focus on solving a problem and using simple interface encapsulation
    • Small: Dapper, contains only the minimum code required to solve a problem
    • Collaboration: PHP components can be well co-operative, grouped together for large projects
    • Test good: Provide testing itself, and have sufficient test coverage
    • Documentation: Complete documentation should be provided to enable developers to easily install, understand and use

2. Component vs Framework

When we choose a framework, we put a lot of tools into the framework, and the framework usually provides a lot of tools, but without providing the tools we need, the pain is passed on to us, and we're looking for and integrating a custom PHP library. It is difficult to integrate third-party code into the framework, because third-party code and frameworks may not use the same interface.

When we choose a framework, we are in the future of the framework, but who can guarantee that a framework is always the best tool to do a job? Large projects that have been in existence for years must have good performance, and should be adjusted at all times, and if you choose the wrong PHP framework, you may not be able to do that. Older PHP frameworks may be slow or outdated due to lack of community support, and these old frameworks are usually written in procedural code, without the use of modern object-oriented code and some new features of PHP, in short, there are a lot of things to consider when deciding whether to use PHP frameworks.

Fortunately, Laravel is doing well in these concerns so that it can stand out in many PHP frameworks, and in a sense, laravel is also a framework based on component development (the core component is its own illuminate library, which relies heavily on third-party components for implementation), Compared to Symfony, it's easy to get started, so it's both extensibility and ease of use. However, Laravel also has some shortcomings, such as Laravel's own components can not be easily decoupled from the Laravel framework (but believe that the situation will be improved, such as its database and queue components can be decoupled). In general, Laravel is still an excellent framework to help us quickly create powerful applications.

So should we use a component or a framework? The answer is, using the right tools to do the right thing, if you can quickly implement small projects with some PHP components, use components, if you have multiple team members developing large projects, and can benefit from the agreed guidelines and structures provided by the framework, use the framework (if it's a tangled frame, Then choose Laravel, which will not disappoint you, and use the framework to guide and accelerate the development of your project.

PS: This sentence also applies to the language of the dispute, with the correct language to do the right thing, nothing less BB, this is the college June to the language of the dispute attitude and position.

3. Using components

Packagist

We look for PHP components in Packagist, a site that collects PHP components, and the best PHP components are found in the packagist.

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

Composer

Packagist is the community that looks for PHP components, and composer is the tool for installing PHP components. Composer is a dependency manager for PHP, running on the command line, you tell composer what components are needed, composer will download and load these components automatically into your project, as simple as that.

Composer and packagist work closely together, if you tell composer that you want to use the Guzzlehttp/guzzle component, composer will get packagist components from Guzzlehttp/guzzle, Find the warehouse address of this component, determine which version to use, and find out the dependencies of this component, and then download the Guzzlehttp/guzzle component and its dependencies to your project.

In addition, composer automatically generates a PSR-compliant autoloader for all of the PHP components in the project, effectively abstracting dependency management and automatic loading, so for the PHP community, composer is the most important add-on tool, and none of them It's not too much to think about the painful days when we used to automate loading manually, such as include, require, spl_autoload_register.

About the installation and use of composer, here do not repeat, please refer to composer Chinese network.

4. Sample Project

Here's a sample project to demonstrate how to use composer and components to develop a PHP application that scans a URL in a CSV file to find the dead chain, which sends an HTTP request to each URL if the HTTP status code returned is greater than or equal to 400. Send this dead chain to standard output. This is a command line application, after development, we will execute this script, pass the path of the CSV file, display the dead chain list in standard output.

Installing components

Before you begin, let's see which tasks can be solved using existing PHP components: We need a component that iterates over the CSV file data, and an HTTP request to each URL in the CSV file, so we also need a component that can send HTTP requests and check HTTP responses.

After browsing packagist, we found the two components of guzzlehttp/guzzle and league/csv for processing HTTP messages, which are used to process CSV data. Below we run the following command at the top level of the project:

Composer require guzzlehttp/guzzlecomposer require league/csv

Composer will depend on installing the vendor directory to the root directory, and after the installation is complete, the Composer.json and Composer.lock files will be generated in the root directory:

The Composer.lock file lists all the PHP components used by the project, as well as the specific version number of the component, which actually locks the project so that the project can only use the specific version of the PHP component. The advantage is that composer will download the specific version listed in this file, regardless of the latest version available in Packagist, you should include the Composer.lock file in version control so that the PHP version used by team members is the same as yours. If your local development and server use the same version of PHP components, you can minimize the bug caused by different component versions.

If you are sure you want to download the latest version of the component and update Composer.lock, you can use the composer Update command.

Auto Load

Next we write the application code, create a scan.php file under the root directory, and then use require to import the autoloader created by composer at the top of the file:

     

Composer created the autoloader is actually a file named autoload.php, saved in the vendor directory, composer download the individual PHP components, the Composer.json file of each component is checked, determine how to load the component, Once this information is available, composer will create a PSR-compliant autoloader for the component locally. This allows us to instantiate any PHP component in the project, which is automatically loaded on demand.

Writing code

Below we formally write the scan.php code using the Guzzle and CSV components:

 
   Get ($csvRow [0]);        Check the HTTP response status code        if ($httpResponse->getstatuscode () >=) {            throw new Exception ();        }    } catch ( Exception $e) {            //Send the dead chain to the standard output            echo $csvRow [0]. Php_eol;}    }

Here we add some URLs, one line at a urls.csv, and at least one is a dead chain:

Then open the 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 the private PHP components and how to create our own PHP components and upload them to packagist.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.