Best Practice series (1)-About PHP components, frameworks, and Composer. 1. what are components?
A component is a set of packaged code and a series of related classes, interfaces, and Trait. it helps us solve a specific problem in PHP applications. For example, if your PHP application needs to send and receive HTTP requests, you can use existing components such as guzzle/guzzle. We use components not to re-implement the implemented functions, but to spend more time on achieving the long-term goal of the project.
Excellent PHP components have the following features:
- Single role: focus on solving a problem and use simple interface encapsulation functions
- Small: small and exquisite, only contains the minimum code required to solve a problem
- Cooperation: PHP components can work together to achieve large-scale projects.
- Good testing: provides testing and has sufficient test coverage.
- Comprehensive documentation: comprehensive documentation should be provided for developers to easily install, understand, and use
2. component vs framework
When we select a framework, we need to invest a lot in the tool of this framework. The framework usually provides a lot of tools, but it does not provide a tool we need, the pain is passed on to us, we are looking for and integrating custom PHP libraries. It is difficult to integrate third-party code into the framework, because the third-party code and framework may not use the same interface.
When we select a framework, we are looking at the future of the framework. but who can ensure that a framework is always the best tool to complete a job? A large project that has been in existence for many years must have a good performance and must be well adjusted at all times. if the PHP framework is selected incorrectly, this may not be possible. Older PHP frameworks may be slow or outdated due to lack of community support. these old frameworks are usually written in procedural code, rather than new object-oriented code and some new PHP features, in short, there are many things to consider when deciding whether to use the PHP framework.
Fortunately, Laravel is doing well in these concerns, so it can stand out from many PHP frameworks. in a sense, laravel is also a component-based development framework (the core component is its own Illuminate Library, which relies heavily on third-party components for function implementation). compared with Symfony, Laravel is easy to get started, so it has both scalability and ease of use. However, Laravel also has some shortcomings. for example, components of Laravel 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 ). In summary, Laravel is still an outstanding framework that can help us quickly create powerful applications.
Should we use components or frameworks? The answer is: Use the right tools to do the right thing. if you can use some PHP components to quickly implement small projects, use the components. if multiple team members develop large projects, in addition, if you can benefit from the agreed principles and structures provided by the framework, use the framework (if you are struggling to use any framework, select Laravel, which won't disappoint you ), the framework can guide and accelerate project development.
PS: This sentence is also applicable to the language competition. if you use the correct language to do the right thing, it's okay. this is the attitude and position of the Emy for the language competition.
3. use 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 you 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 for finding PHP components, and Composer is the tool for installing PHP components. Composer is the dependency manager of PHP. it is as simple as running it in the command line and telling Composer which components are needed. Composer downloads and automatically loads these components into your project.
Composer works closely with Packagist. if you tell Composer to use the guzzlehttp/guzzle component, Composer obtains the guzzlehttp/guzzle component from Packagist and finds the repository address of the component, determine the version you want to use. you can also find the dependencies of this component and then download the guzzlehttp/guzzle component and its dependencies to your project.
In addition, Composer will automatically generate an automatic loader that complies with the PSR standard for all PHP components in the project, effectively abstracting dependency management and automatic loading. Therefore, for the PHP community, composer is one of the most important additional tools. you can hardly imagine how difficult it is to manually implement automatic loading using include, require, and spl_autoload_register.
For more information about how to install and use Composer, see Composer.
4. example project
The following uses 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 dead links, the application sends an HTTP request to each URL. 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 chain list in the standard output.
Install components
Before starting, let's take a look at which tasks can be solved by using the existing PHP components: We need a component that can iteratively process csv file data, and send an HTTP request to each URL in the csv file, therefore, you also need a component that can send an HTTP request and check the HTTP response.
After browsing Packagist, we find the guzzlehttp/guzzle and leags/csv components. The former is used to process HTTP messages, and the latter is used to process CSV data. Run the following command at the top of the project:
composer require guzzlehttp/guzzlecomposer require league/csv
The Composer will install the dependencies to the vender directory in the root directory. after the installation is complete, the composer. json and composer. lock files will be generated under the root directory:
The composer. lock file lists all PHP components used by the project and the specific version number of the component. this actually locks the project and allows the project to only use PHP components of a specific version. The advantage is that composer will download the specific version listed in this file, regardless of the latest version available in Packagist, you should set composer. the lock file is included in version control, so that the PHP version used by the team members is the same as that of you. if the PHP component version used by the local development and server is the same, the bug 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.
Automatic loading
Next we will compile the application code, create a scan. php file under the root directory, and then import the auto loader created by Composer using require at the top of the file:
The automatic loader created by Composer is actually named autoload. php files are stored in the vendor directory. when Composer downloads various PHP components, it checks the composer of each component. json file to determine how to load the component. after obtaining this information, Composer will create an automatic loader for the component locally that complies with the PSR standard. In this way, any PHP components in the project can be instantiated and automatically loaded as needed.
Write code The following code uses the Guzzle and CSV components to compile scan. php:
Get ($ csvRow [0]); // Check the HTTP response status code if ($ httpResponse-> getStatusCode () >=400) {throw new Exception ();}} catch (Exception $ e) {// send the dead chain to the standard output echo $ csvRow [0]. PHP_EOL ;}}
Next we will add some URLs in urls.csv, one row, and at least one is a dead link:
Open the terminal and run the scan. php script:
php scan.php urls.csv
We passed in two parameters: the first is the path of the script file scan. php, and the other is the path of the CSV file. The output is as follows:
In the next section, we will discuss private PHP components and how to create your own PHP components and upload them to Packagist.