Best Practice series (II)-talk about PHP private components and how to create your own PHP components

Source: Internet
Author: User
Tags autoload composer install git commands
Best Practice series (II)-talk about PHP private components and how to create your own PHP components 1. Private components

Most of the time, we use open-source components that are publicly available. but sometimes, if the company uses PHP components developed internally, it cannot be open-source based on license and security issues, you need to use private components. This is a piece of cake for Composer.

Composer can be used to manage private PHP components in the repository to be authenticated. when you execute the composer install or composer update command, if the component repository requires authentication creden, Composer will remind you to enter authentication information, in addition, Composer also asks whether to save the authentication credential of the repository in the local auth. json file (and composer. json is placed at the same level ). The following is an example of auth. json content:

{    “http-basic”: {        “laravelacademy.org”: {            “username”: “your-username”,            “password”: “your-password"        }    }}

It is best not to put auth. json in version control. we want the project developers to create their own auth. json files and save their own authentication creden.

If you do not want to wait until Composer asks you for authentication creden:, you can use the following command to manually tell Composer the authentication creden: of the remote device:

composer config http-basic.laravelacademy.org your-username your-password

In this example, http-basic tells Composer that we want to add authentication information for the specified domain name. Laravelacademy.org is the host name used to identify the device that stores the private component repository. the last two parameters are the user name and password. By default, this command saves creden。 in the auth. json file of the current project.

You can also use the-global tag to save authentication creden。 in the global system. With this flag, Composer uses this credential in all projects on the local device.

composer config --global http-basic.laravelacademy.org your-username your-password

Save Global creden in ~ /. Composer/auth. json. if you are using a Windows system, the global creden。 are saved in the APPDATA %/Composer folder.

2. create components

Now you should know how to find and use PHP components. next we will discuss how to create PHP components. Creating a PHP component is a good way to share your work results with members of the PHP community. The PHP community is happy to share and help others. if you use open-source components in your applications, let us know, creating innovative new open-source components is the best way to return to the community.

Note: Do not re-compile existing components. if it is to improve the existing components, you can send the improvement to the original component in the pull request. Otherwise, the PHP ecosystem will be flooded with repeated components.

Namespace

Before setting a namespace, you must first determine the vendor name and package name, such as laravel/framework. to ensure global uniqueness, it does not exist in Packagist.

Each component has its own namespace. here, we often mistakenly assume that the component namespace must be consistent with the component manufacturer name and package name, the namespace used by the component is independent of the vendor name and package name of the component. the vendor name and package name are only used to enable Packagist and Composer to identify the component, the component namespace is used in PHP code.

File system structure

The file system structure of the PHP component is basically determined:

  • Src: This directory is used to store the source code of the component.
  • Tests: stores the test code of the component.
  • Composer. json: Composer configuration file, used to describe components, declare component dependencies, and automatically load configurations.
  • README. md: this Markdown file provides information about components, user instructions, software licenses, etc.
  • CONTRIBUTING. md: this Markdown file tells others how to contribute to this component.
  • LICENSE: a plain text file that declares a software LICENSE for the component
  • CHANGELOG. md: Markdown file, listing the changes introduced by the component in each version
Composer. json

The PHP component must contain the composer. json file, and the content of this file must be valid JSON. Composer will use the information in this file to find, install, and automatically load the PHP component. The composer. json file also contains information about components in the Packagist directory.

Create a new component directory (~ /Packages/urlloads), and then generate the composer. json file in the urlloads Directory using the following command:

composer init

Then in the Wizard, we will enter the composer. json content step by step according to the prompt Wizard:

Press enter to generate the corresponding composer. json file. we will modify the file as follows:

{    "name": "laravelacademy/urlscanner",    "description": "Scan URLs FROM A CSV FILE AND REPORT INACCESSIBLE URLs",    "keywords": ["url", "scanner", "csv"],    "homepage": "http://laravelacademy.org",    "license": "MIT",    "authors": [        {            "name": "sunqiang",            "email": "yaojinbu@163.com"        }    ],    "support": {        "email": "yaojinbu@163.com"    },    "minimum-stability": "dev",    "require": {        "php": ">=5.4.0",        "guzzlehttp/guzzle": "~5.0"    },    "require-dev": {        "phpunit/phpunit": "~4.3"    },    "suggest": {        "league/csv": "~6.0"    },    "autoload": {        "psr-4": {            "LaravelAcademy\\UrlScanner\\": "src/"        }    }}

Let's take a closer look at this document to see what each part actually means:

  • Name: The manufacturer name and package name of the component. it is also the component name in Packagist.
  • Description: brief description of components.
  • Keywords: keyword used to describe an attribute
  • Homepage: Component website URL
  • License: software license for PHP components (for more software licenses, refer to: http://choosealicense.com /)
  • Authors: Author information array
  • Support: How component users obtain technical support
  • Require: component dependent on
  • Require-dev: dependencies required to develop this component
  • Suggest: Recommended Components
  • Autoload: Tells the Composer auto loader how to automatically load this component.
READEME. md

This is usually the first file you read, especially for components hosted on Github and Bitbucket. The standard READEME. md file must provide at least the following information:

  • Component name and description
  • Installation Instructions
  • Instructions for Use
  • Test description
  • Contribution
  • Supported resources
  • Author information
  • Software license
Implementation components

Run the following command to install the dependency:

composer install

This command will install the dependent components to the vendor directory and generate an automatic loader.

Now we want to implement the specific functions of the component. In this step, we need to write the classes, interfaces, and Trait that make up the PHP components. what classes to write and how many classes to write depend entirely on the functions of the PHP components. However, all classes, interfaces, and Trait in the component must be placed in the src directory.

For this component, I only need to create a class secret in the sub-namespace Url, which is located in composer. in the LaravelAcademy/urlemy namespace set in the json file, the category class is stored in src/Url/templates. php file. The logic implemented by the Scanner class is the same as the URL Scanner sample application in the previous section, but now we need to encapsulate the URL scanning function in a PHP class:

 Urls = $ urls; $ this-> httpClient = new Client ();} /*** get the HTTP status code for accessing the specified URL ** @ param $ url * @ return int */public function getStatusCodeForUrl ($ url) {$ httpResponse = $ this-> httpClient-> get ($ url); return $ httpResponse-> getStatusCode ();} /*** get dead chain *** @ return array */public function getInvalidUrls () {$ invalidUrls = []; foreach ($ this-> urls as $ url) {try {$ statusCode = $ this-> getStatusCodeForUrl ($ url);} catch (\ Exception $ e) {$ statusCode = 500;} if ($ statusCode> = 400) {array_push ($ invalidUrls, ['URL' => $ url, 'status' => $ statusCode]) ;}} return $ invalidUrls ;}}

Instead of parsing and iteratively processing a CSV file, we pass a URL array to the constructors of the category class, because we should try our best to make the class of the scanned URL generic. If the CSV file is processed directly, the usage of this component is limited. We open the source of the obtained URL to users so that they can retrieve it from files, arrays, or CSV files. So back to composer. json above, we declare the league/csv component in suggest, but it is recommended that you install it, not required.

Submit to Packagist

First, we will submit the code to GitHub (note that the vendor directory is added to. gitignore) repository (my nonfu/urlloud ):

The involved git commands are as follows:

git initgit remote add origin https://github.com/nonfu/urlscanner.gitgit add .git commit -m “urlscanner"git pull origin mastergit push origin master

In this way, the local component is submitted to the GitHub repository:

Then in Packagist login via GitHub account, submit components via https://packagist.org/packages/submit, enter the GitHub repository address just submitted in the input box:

After the check succeeds, click submit to submit the component to Packagist:

The red warning means that we need to use the GitHub Service Hook to create a Hook in GitHub and notify Packagist every time the component's GitHub repository is updated.

3. use components

So far, we have successfully submitted our components to Packagist. now anyone can use Composer to install this URL scanner component and use it in their PHP applications. Run the following command on the terminal to install the component:

composer require laravelacademy/urlsanner dev-master

Then we use the following in our code:

 getInvalidUrls());
Related Article

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.