Home PHP Framework ThinkPHP How to import third-party libraries in ThinkPHP

How to import third-party libraries in ThinkPHP

Jun 03, 2023 pm 05:15 PM
thinkphp

Third-party class library

Third-party class libraries refer to other class libraries besides the ThinkPHP framework and application project class libraries. They are generally provided by third-party systems or products, such as class libraries of Smarty, Zend and other systems.

For the class libraries imported earlier using automatic loading or the import method, the ThinkPHP convention is to use .class.php as the suffix. Non-such suffixes need to be controlled through the import parameters.

But for the third type of library, since there is no such agreement, its suffix can only be considered to be php. In order to easily introduce class libraries from other frameworks and systems, ThinkPHP specifically provides the function of importing third-party class libraries. Third-party class libraries are uniformly placed under the ThinkPHP system directory/Vendor and imported using the vendor method.

Vendor method

grammar:

boolenvendor(class,baseUrl,ext)

Parameter Description:

Parameter Description

Class is required, indicating the class library to be imported, in the form of a namespace.

baseUrl is optional, indicating the base path of import. If omitted, the system uses the ThinkPHP system directory/Vendor directory.

ext is optional, indicating the imported class library suffix, the default is .php.

The difference from the import method is that the default import path of the vendor method is the ThinkPHP system directory/Vendor directory, and the default suffix is ​​.php.

Personal experience sharing:

When we want to introduce a third-party extension into ThinkPHP, and the third-party extension is not written according to ThinkPHP specifications, we need to place the third-party extension in the Library/Vendor directory. Of course, this is for ThinkPHP3.2 In other words, the lower version depends on the situation.

Then when you need to use a third-party extension in a Controller or function, you can directly use the vendor() method to reference it.

Third-party library directory structure:

​Used in the function function:

the first method:

Vendor('Phpqrcode.phpqrcode');

Copy code

Copy code

/**

*Generate QR code

*@paramstring$urlurl connection

*@paraminteger$size size pure number

​*/

functionqrcode($url,$size=4){

Vendor('Phpqrcode.phpqrcode');

​if(strpos($url,'http')===false){

​$url='http://'.$url;

}

QRcode::png($url,false,QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000);

}

Copy code

Copy code

The second method:

require'./ThinkPHP/Library/Org/Nx/class.phpmailer.php';

require'./ThinkPHP/Library/Org/Nx/class.smtp.php';

Copy code

Copy code

/**

*send email

*@paramstring$address The email address to be sent to multiple addresses needs to be written in array form

*@paramstring$subjecttitle

*@paramstring$content content

*@returnboolean is successful

​*/

​functionsend_email($address,$subject,$content){

​$email_smtp=C('EMAIL_SMTP');

​$email_username=C('EMAIL_USERNAME');

​$email_password=C('EMAIL_PASSWORD');

​$email_from_name=C('EMAIL_FROM_NAME');

​if(empty($email_smtp)||empty($email_username)||empty($email_password)||empty($email_from_name)){

returnarray("error"=>1,"message"=>'The mailbox configuration is incomplete');

}

require'./ThinkPHP/Library/Org/Nx/class.phpmailer.php';

require'./ThinkPHP/Library/Org/Nx/class.smtp.php';

​$phpmailer=new\Phpmailer();

//Set PHPMailer to use SMTP server to send Email

​$phpmailer->IsSMTP();

//Set to html format

​$phpmailer->IsHTML(true);

//Set the character encoding of the email'

​$phpmailer->CharSet='UTF-8';

//Set up SMTP server.

​$phpmailer->Host=$email_smtp;

//Set to "Require verification"

​$phpmailer->SMTPAuth=true;

//Set username

​$phpmailer->Username=$email_username;

//set password

​$phpmailer->Password=$email_password;

//Set the From field of the email header.

​$phpmailer->From=$email_username;

//Set the sender name

​$phpmailer->FromName=$email_from_name;

//Add the recipient address, which can be used multiple times to add multiple recipients

​if(is_array($address)){

​foreach($addressas$addressv){

​$phpmailer->AddAddress($addressv);

}

}else{

​$phpmailer->AddAddress($address);

}

//Set email title

​$phpmailer->Subject=$subject;

//Set email text

​$phpmailer->Body=$content;

//send email.

​if(!$phpmailer->Send()){

​$phpmailererror=$phpmailer->ErrorInfo;

returnarray("error"=>1,"message"=>$phpmailererror);

}else{

returnarray("error"=>0);

}

}

Copy code

Copy code

The third method:

Alipay library directory structure

vendor('Alipay.AlipaySubmit','','.class.php');

Note: The default suffix loaded by Vendor is

of .php Parameter 1: Required, indicating the class library to be imported, using the namespace method

Parameter 2: Optional, indicating the base path of import. If omitted, the system uses the ThinkPHP system directory/Vendor directory.

Parameter three: Optional, indicating the imported class library suffix, the default is .php.

Alipay third-party case code:

Copy code

Copy code

/**

* Jump to Alipay payment

*@paramarray$order order data must include out_trade_no (order number), price (order amount), subject (product name title)

​*/

functionalipay($order){

vendor('Alipay.AlipaySubmit','','.class.php');

//Get configuration

​$config=C('ALIPAY_CONFIG');

​$data=array(

"_input_charset"=>$config['input_charset'],//Encoding format

"logistics_fee"=>"0.00",//Logistics fee

"logistics_payment"=>"SELLER_PAY",//Logistics payment method SELLER_PAY (the seller bears the freight), BUYER_PAY (the buyer bears the freight)

"logistics_type"=>"EXPRESS",//Logistics type EXPRESS (express), POST (surface mail), EMS (EMS)

"notify_url"=>$config['notify_url'],//Link to receive payment status notification asynchronously

"out_trade_no"=>$order['out_trade_no'],//Order number

"partner"=>$config['partner'],//Partner is obtained from the Alipay Merchant Version Personal Center

"payment_type"=>"1", //The payment type corresponds to the payment_type parameter in the request, and is returned as is. Just set it to 1

"price"=>$order['price'],//The order price unit is yuan

//"price"=>0.01,////Price adjustment is used for testing

"quantity"=>"1",//price and quantity can replace total_fee. That is, if total_fee exists, price and quantity cannot exist; if price and quantity exist, total_fee cannot exist. (I didn’t understand; okay; just ignore this parameter)

"receive_address"=>'1',//The method of instant payment to the consignee address can ignore this parameter

"receive_mobile"=>'1',//Ignore the method of instant payment of the consignee's mobile phone number

"receive_name"=>'1',//Just ignore the method of instant payment of the name of the consignee

"receive_zip"=>'1',//You can ignore the instant arrival method of the consignee's zip code

"return_url"=>$config['return_url'], //Page jump synchronization notification page path After Alipay processes the request, the current page automatically jumps to the http path of the specified page in the merchant website.

"seller_email"=>$config['seller_email'],//email is obtained from the Alipay Merchant Version Personal Center

"service"=>"create_direct_pay_by_user", //The interface name is fixed to create_direct_pay_by_user

"show_url"=>$config['show_url'], //Product display URL, hyperlink to product display on the checkout page.

"subject"=>$order['subject']//Product name, product title/transaction title/order title/order keyword, etc.

);

​$alipay=new\AlipaySubmit($config);

​$new=$alipay->buildRequestPara($data);

​$go_pay=$alipay->buildRequestForm($new,'get','pay');

echo$go_pay;

}

Copy code

Copy code

However, when I put PHPMailer in the Vendor directory, it ran fine on this machine. Recently, when I uploaded the program to the server, it directly prompted Class "PHPMailer" not found and then ran it on this machine again, and it was still correct! As you can know from the previous blog, I passed vendor('PHPMailer.class#PHPMailer');

This line of code introduces PHPMailer. Since it prompts that the PHPMailer class cannot be found, it means that it has not been introduced correctly. Why is this?

I took a cursory look at the source code of the vendor() method, and found out that the vendor() method actually assembles the parameters of the import() method, and then leaves it to the import() method for processing. Looking at the source code of the import() method, we found that in the import() method, the analysis of the above incoming parameters is actually to replace ’.’ with ’/’, and ’#’ with’ ;.’, baseurl is automatically added by the vendor() method, pointing to the Vendor directory. So the parameters in the vendor() method above are eventually parsed into the following directory:

Library/Vendor/PHPMailer/class.PHPMailer.php

The actual directory address of PHPMailer's entry file is:

Library/Vendor/phpmailer/class.phpmailer.php

The content is the same! However, I am using a Linux server, so the case is strictly distinguished, so of course I cannot successfully import this class. The solution is to introduce vendor() and change it to:

vendor(‘phpmailer.class#phpmailer’)

In addition, you should pay attention to one thing when using PHPMailer. If PHPMailer uses SMTP to send emails, PHP needs to support fsockopen, so we need to modify the disable_functions in php.ini to delete fscokopen, otherwise a running error will occur:

​fsockopen()hasbeendisabled

It can be obtained through the ErrorInfo attribute of PHPMailer!

The above is the detailed content of How to import third-party libraries in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles