"PHP base Class Library" Prototype prototype teaching articles

Source: Internet
Author: User
Tags api manual php template
"PHP Basic Class Library" Prototype prototype teaching articles!

Preface Hello everyone I am: The stone is not easy, today I brought the PHP base Class Library prototype version of the teaching article, so my work line has been divided into three categories, namely: JavaScript front-end Framework (package library), PHP template engine, and PHP base Class library. This kind of library lasted intermittently developed nearly 3 months, during a large period of the gap period did not develop, so it is very ashamed to have been dragged until now to calculate the release also had a mind. The library is divided into 5 major modules, namely: database Operation module , paging module , file upload module , thumbnail module and Verification code module .

Get This article is the teaching part of this kind of library, through a number of examples of source code, to teach you to learn to use this type of library. Before that, alumni can visit my personal website to get access to the source code of the library, as well as to view and run the API documentation for the demo program and Reading library. Visit the following link to transfer to the target content. This article will be published separately to: Blog Park ,51CTO,iteye,CSDN and other 4 technical blog, for more alumni to see!

My website:http://www.shibuyi.net

Example Demo:http://www.shibuyi.net/demo/php/foundation_classes/prototype/

API Document:http://www.shibuyi.net/api/php/foundation_classes/prototype/

Operating Environment This class library has also made a lot of restrictions on PHP operating environment, currently only support:PHP 5.2,5.3 and 5.4, below or above this range will not be able to run this class library; also for PHP Extensions have also made strict restrictions on the Windows platform, for example, PHP must be open at the same time:php_mysql.dll,php_mysqli.dll,php_ 4 extensions such as Mbstring.dll and Php_gd2.dll will work perfectly.

directory Structure below we formally entered the class library of the teaching body, I explained the order of: Database operation module, paging module, file upload module, thumbnail module and Verification code module, before we begin the class library file directory structure to do a detailed introduction to the demonstration program, we can go to the official website to download.

For the class Library demonstration program's file directory structure, then I each to explain each directory and the file meaning, two outside the author uses the Windows 7 environment Zendstudio 7.2.1 integrated development Environment, So if you are using a development platform in a different environment, the location and icon of the file directory may be slightly different.

classes_prototype : The project name for the entire class library demo program is also the root directory name for the entire project, and the root of the demo program that you download is the Chinese name, so please correct the English name before you run it. The Chinese name is not supported under some platforms.

/classes : For the core directory of the entire demo program, which holds all the class files in the class library, if you want to develop your own project or learn the class library, you can separate the class files in the classes directory to move to your own project.

  1. /classes/database.class.php : The file is the primary file for the database operations class. (import file, external direct call)
  2. /classes/fileupload.class.php : This file is the main file for the file upload class. (import file, external direct call)
  3. /classes/interfacedatabase.class.php : The file is an interface file for the database operations class. (interface file, external cannot be called)
  4. /classes/newdatabase.class.php : The file is a mysqli database operation class file. (Non-portal file, not recommended for external direct calls)
  5. /classes/olddatabase.class.php : This file is a MySQL database operation class file. (Non-portal file, not recommended for external direct calls)
  6. /classes/page.class.php : The file is the main file for the paging class. (import file, external direct call)
  7. /classes/thumbnail.class.php : The file is the primary file for the thumbnail class. (import file, external direct call)
  8. /classes/tool.class.php : The file is a public utility class for the class library, and the class library file inherits the class method. (Abstract class file, external cannot be called)
  9. /classes/validatecode.class.php : The file is the primary file for the Captcha class. (import file, external direct call)

/fonts : The font file directory for the demo program, which is mainly available for thumbnails and captcha use.

/includes : A common file directory for the demo program, primarily for initializing and public files.

/styles : The CSS style catalog for the demo program, including the pagination style for the pagination class.

/uploads : For the file upload class root directory, you can modify the root directory according to the needs of the name, if the directory does not exist, the file upload class will be automatically created, detailed operation and then refer to the file upload class is explained in detail.

/watermark : The watermark Picture Directory for the demo program, which holds the watermark image file for the thumbnail image.

/classes_prototype.sql : For the Demo program database file, you can directly through the database (MySQL) tool to import it, or the database function can not be demonstrated.

/code.php : Configures and outputs files for the demo program's CAPTCHA.

/thumbnail.php : Configure and output files for the thumbnail of the demo program.

Database Classes first, let's look at the use of database modules. The database module is also the most complex module of this kind of library, which contains 3 class files and 1 interface files, we will take a look at the execution of the demo program before we explain.

The above is the database and paging section of the demo program. When explaining the database operation, please refer to the API manual to learn the best results. The order in which the class library is explained is followed by the API's interface ordering. Let's go with the actual code.

1. Database initialization

Before we start, we need to figure out what the 4 class files of the database module are for. First, the database is the external calling class of the DB module, and all the external APIs that can be called outside the database module are integrated and can be manipulated directly after instantiation. Newdatabase and Olddatabase, respectively, are mysqli and MySQL Database extension encapsulation class, its functions have been integrated into the database class, so there is no need to separate calls, and it is not recommended to separate calls. The final Interfacedatabase interface class is a specification issue that addresses the public API for the first 3 class libraries. Then after figuring out what each class file does, our next step is to configure the database and configure it correctly so that the database module can execute properly. All configurations and operations are done using the Database class. Set database operation mode//True for mysqli extension, false for MySQL extension, default to: truedatabase:: $type = ture;//"Required" to set the database address, before and after the space is automatically removed, the default is: LOCALHOSTD Atabase:: $host = ' localhost ';//' Required ' to set the database port, default: 3306Database:: $port = 3306;//"Required" to set the user name, before and after the space is automatically removed, the default is: Rootdatabase  :: $username = ' Louis ';//"required" to set the user password, default: null character database:: $password = 123456;//Set the name of the databases, the front and back spaces are automatically removed, the default is: null character database:: $name = ' classes_prototype ';//Set character encoding, the front and rear spaces will be automatically removed, the default is: utf8database:: $charset = ' UTF8 ';//Set SQL statement escape switch//True to open escape switch, false for off Closed escape switch, the default is: truedatabase:: $decodeSwitch = false;//instantiation of the database, the previous configuration information takes effect $DB = new Database ();

The above code is the configuration of the database operation, only the configuration of the required options are filled in correctly, then the database is instantiated to be able to be properly connected. Then we use the API to the database data: increase, delete, change, check and other operations.

2. Select a database

Specify the database; if database: $name = ' ', then set_name ()//is not called when the DB is instantiated ()//Only database:: $name is assigned, that will call Set_name () Select the database/reset Database name:: $name = ' classes_prototype ';//Select the name of the database $db, Set_name (); No return value

3. Set character encoding

Specifies the character encoding; here, as with a specified database, if you: $charset = ' ' then new Database () will not call Set_charset ()//When database:: $charset is assigned, then Will call Set_charset ()//Reset character encoding database:: $charset = ' UTF8 ';//Select the character encoding $db-set_charset (); No return value

4. Database queries

Get previous step insertion operation Id$db-get_id (); Returns the positive integer value if no INSERT INTO INSERT SQL statement is executed, then returns: 0//gets the total number of record rows, just write the table name to $tablename = ' cp_phone '; $tableName is the table name $db-Get_total ($tableName); Returns a positive integer value, or, if there is no record, returns: 0//destroy result set $db-Free_result (); No return value//Get record number of rows $mode = false; $mode indicates whether to destroy the current query result set, True to destroy, false to ignore $db-get_rows ($mode); Returns a positive integer value, or, if there is no record, returns: 0//gets the number of operations rows $db, get_affected (); Returns a positive integer value, if no: Add, delete, change, check operation, then return: 0//gets a record line//$sql for a single SQL query SELECT statement $sql = "Select ' id ', ' phone ' from ' Cp_phone ' WHE RE ' id ' = 1 LIMIT 1; "; $mode = false; $mode indicates whether to destroy the current query result set, True to destroy, false to ignore $db-Get_one ($sql, $mode); Returns the object//gets more than one record line//$sql for a single SQL query SELECT statement $sql = "Select ' id ', ' phone ' from ' cp_phone ' WHERE TRUE;"; $mode = false; $mode indicates whether to destroy the current query result set, True to destroy, false to ignore $db-Get_all ($sql, $mode); Returns a one-dimensional array object//executes multiple SQL queries//$SQLS A SELECT statement for multiple SQL queries, through the ";" Number interval SQL statement $sqls = "; $sqls. =" Select ' id ', ' phone ' from ' cp_phone ' WHERE ' id ' = 1 LIMIT 1; "; $sqls. = "Select ' id ', ' phone ' from ' Cp_phone ' WHERE ' id ' = 2 LIMIT 1; "; $sqls. = "Select ' id ', ' phone ' from ' cp_phone ' WHERE ' id ' = 3 LIMIT 1;"; $db-Set_mutiple ($SQLS); Returns a two-dimensional array object

5. Database increase, deletion, change operation

Escape string; if Database: $decodeSwitch = True Then every time you execute a SQL statement query or operation, the SQL statement is first escaped//vice versa if False then the escape of the SQL statement is ignored and the $s is executed directly Tring = "SET NAMES ' utf8 ';"; $string is the string that needs to be escaped, most of the time is the SQL statement//The escape of the string, for example: \, ', ' and other special character leading will be added backslash $db-decode ($string);  Returns the escaped string//Execute Action statement (new, modified, deleted)//$sql for a single SQL add, delete, change statement $sql = "UPDATE ' cp_phone ' SET ' phone ' = ' 13034567890 ' WHERE ' id ' = 1 LIMIT 1; "; $db-Set_operation ($sql); Returns the number of record rows after execution of the response: positive integer value//execute multiple SQL operations (new, Modified, deleted)//$SQLS for multiple SQL Add, delete, change statement $sqls = "; $sqls. =" UPDATE ' cp_phone ' SET ' phone ' = ' 1 3034567890 ' WHERE ' id ' = 1 LIMIT 1; "; $sqls. = "UPDATE ' cp_phone ' SET ' phone ' = ' 13078903456 ' WHERE ' id ' = 2 LIMIT 1;"; $sqls. = "UPDATE ' cp_phone ' SET ' phone ' = ' 15634560000 ' WHERE ' id ' = 3 LIMIT 1;"; $db-Set_mutiple ($SQLS); Returns the number of record rows for each SQL statement response after execution: one-dimensional array positive integer value//execution transaction//$sqls for multiple SQL increment, delete, change statement $sqls = "; $sqls. =" DELETE from ' cp_phone ' WHERE ' id ' = 1 LIMIT 1; "; $sqls. = "DELETE from ' cp_phone ' WHERE ' id ' = 2 LIMIT 1;"; $sqls. = "DELETE from ' cp_phone ' WHERE ' id ' = 3 LIMIT 1; "; $db-Transaction ($SQLS); Returns a Boolean value that is true for execution success, false for execution failure

6. Close the database

Destruction method: Shut down the database//Shut down the database API does not need to call manually, after the execution of the page script execution, the destructor will be executed automatically, so the shutdown of the database operation is complete automatically $db-__destruct ();

Pagination Class Paging Module A total of 1 classes of files, for paging execution, a total of two output styles, respectively: digital paging, text paging.

1. Paging initialization

"Required" setting shows the number of bars per page, by default: 10Page:: $pageSize = 10;//"Required" sets the total number of database records by default: 0Page:: $total = $db, Get_total (' Cp_phone ');//Set points Page primary key, before and after the space is automatically removed, the default is: pagepage:: $pageKey = ' page ';//Set the paging anchor, the front and rear spaces will be automatically removed, the default is: pPage:: $pageAnchor = ' P ';//Set paging anchor switch, true to open anchor point function, false to turn off the anchor point function, default to: falsepage:: $anchorSwitch = true;//Set Paging style switch, true number page style, false for text page style, default to: Truepage:: $ Styleswitch = true;//Sets the number paging length, by default: 2Page:: $bothLength = 4;//Instantiate paging, all previous configuration information takes effect $page = new page ();

2. Paging output

Output current page $page, get_page ()//return True Value//Output Limit$page-get_limit ()//return limit string, for example: limit 0,10//output Paging style//if Pa GE:: $styleSwitch true to output the HTML string of the digital pagination//and false to output text pagination HTML string $page-Page_style ()//return HTML style string

File Upload class File Upload Module A total of 1 class files.

1. Upload Initialization

"Required" setting the upload primary key, the blank space will be automatically removed, the default is: null character fileupload:: $uploadKey = ' up_img ';//set a new file name, both spaces will be automatically removed, the default is: null character//if NULL character, Then the file name will be replaced by the date time FileUpload:: $fileName = ";//Set the upload root directory, both sides of the space will be automatically removed, the default is: '/uploads/'//directory on both sides of the forward and backward, plus or not, upload classes are added automatically FileUpload :: $rootDir = ' uploads ';//Set the upload subdirectory, the blank space will be automatically removed, the default is: null character//directory on both sides of the backslash, plus or no, upload class are added automatically//if it is a null character, then the subdirectory will be replaced by a datetime fileupload:: $ Childdir = ' images ';//Set legal capacity by default: 0FileUpload:: $fileSize = 1;//Set capacity unit, default: ' B '//The capacity unit is not case-sensitive: B (bytes), k/kb (Kbytes), M/MB (MBytes), G/GB (gigabytes), T/TB (FileUpload):: $sizeUnit = ' M ';//Set legal type, default: null character//type is in two formats, one is a string format, and the other is an array format FileUpload:: $ FileType = Array (' Image/jpeg ', ' image/pjpeg ', ' image/jpg ', ' image/png ', ' image/x-png ', ' image/gif ');//Keep the original switch, The default is: false//true to turn on the original, false to close the original fileUpload:: $sourceSwitch = false;//Perform the upload, the previous settings are all in effect $fileupload = new FileUpload ();

2. Get the path

Get upload file path $fileupload-Get_path (); Return the uploaded file path to: string

Thumbnail class thumbnail module A total of 1 classes of files, for the thumbnail image execution.

1. Thumbnail initialization

"Required" to set the picture path, the spaces are automatically removed, the default is: null character thumbnail:: $path = ' uploads/images/201504162043361429188216.jpg ';//Set white background switch, true For white background, false for black background, default to: Falsethumbnail:: $whiteSwitch = false;,//Set output mode switch, true for file output, false for browser output, default: Falsethumbnail:: $exportSwitch = false;//Sets the uniform type switch, true to turn on the unified type, false to turn off the unified type, default to: Truethumbnail:: $typeSwitch = true;//Set the unified picture type, The blank space is automatically removed, the default is: ' PNG '//Currently only supported: PNG, JPEG, GIF three format picture thumbnail:: $imageType = ' png ';//Set the thumbnail, both spaces will be automatically removed, the default is: '% '// There are three kinds of abbreviations:% (abbreviated percentage), = (equal to the abbreviation), = = (fixed width higher proportion of the abbreviated) Thumbnail:: $thumbnailType = ' = = ';//Set percentage example, default is: 50Thumbnail:: $percent = 50 ;//Set equal proportions, default: 100Thumbnail:: $proportion = 100;//Set fixed width, default: 100Thumbnail:: $fixedWidth = 280;//Set fixed height, default: 100Thumbnai L:: $fixedHeight = 160;//Set watermark switch, true to turn watermark on, false to turn off watermark, default to: Falsethumbnail:: $watermarkSwitch = true;//Set Text watermark switch, true to text This watermark, false is the picture watermark, the default is: Falsethumbnail:: $watermarkText = false;//Set the watermark text, both sides of the space will be automatically removed, the default is: ' Thumbnail watermark ' Thumbnail:: $text = ' PHP base Class library ';//Set Watermark font path, both spaces are automatically removed, default: null character//font file must be: TTF format thumbnail::$fontPath = ' FONTS/MSYHBD. TTF ';//Set the watermark picture path, the blank space will be automatically removed, the default is: empty character//watermark picture width must be less than one-second of the thumbnail, the height must be less than One-fourth of the thumbnail, will be displayed thumbnail:: $watermarkPath = ' watermark /watermark.png ';//Set the watermark font size by default: 15Thumbnail:: $fontSize = 15;//Set border, true to open border, false to close border, default to: Falsethumbnail:: $ Borderswitch = true;//instanced thumbnail, before setting all to effective new Thumbnail ();

Verification Code Class Verification code module A total of 1 classes of files, for the verification code execution.

1. Verification Code Initialization

Set the factor type, the space on both sides is automatically removed, the default is: ' En-num '//currently supports three types, namely: En (letter), CN (kanji), num (number)//If there are multiple formats, you need to add "-" between the two different formats Used to split Validatecode:: $characterType = ' cn-en-num ';//Set Output mode, true for file output, false for browser output, default to: Falsevalidatecode:: $ Exportswitch = false;//Set the output path, the blank space will be automatically removed, the default is: null character Validatecode:: $path = './';//Set the CAPTCHA picture name, both spaces will be automatically removed, the default is: ' Code ' Validatecode:: $name = ' code ';//Set the number of CAPTCHA characters, default is: 4ValidateCode:: $codeLength = 6;//Set the captcha picture type, both sides of the space will be automatically removed, the default is: ' PNG '//currently only supported Three formats: PNG, JPEG, Gifvalidatecode:: $imageType = ' png ';//Set the CAPTCHA picture width by default: Validatecode:: $width = 200;//Set the captcha picture height, The default is: 50ValidateCode:: $height = 50;//Set the noise switch, true to turn on noise, false to turn off noise, default to: Truevalidatecode:: $snowSwitch = true;//Set the number of noise. Think: 100ValidateCode:: $snowTotal = 100;//Set the interference line switch, true to turn on the interference line, false to turn off the interference line, the default is: Truevalidatecode:: $lineSwitch = true;// The number of interference lines, the default is: 10ValidateCode:: $lineTotal = 10;//Set the font path, both spaces are automatically removed, the default is: the null character//character file must be: TTF format validatecode:: $fontPath = ' fon TS/MSYHBD. TTF ';//Set the font size by default: 20ValidateCode:: $fontSize = 20;//Set Border switch, true to open border, FALSE is a closed border, the default is: Falsevalidatecode:: $borderSwitch = true;//instantiation of the Verification code class, the above settings all take effect $validatecode = new Validatecode (); 

2. Get the Verification code

Output Verification Code character $validatecode-Get_code (); Returns the generated CAPTCHA string, distinguishing the letter case

Conclusion after a few days of intermittent polishing, this kind of library teaching article finally to the end. In the end, I want to give you a preview of what features will be added to the next class library version. First of all, the database module will be specifically for the SQL statement to add, delete, change, check for integrated encapsulation, external calls more simple, the paging module will increase the form page number jump function, when the amount of data is very large even if the digital paging, want to jump to the middle of a page is not very convenient, and the form page number is a good solution File upload module will be broken down in the image upload, and for the image upload to make more specific features, such as: limit the size of the image upload, thumbnail module will be for the watermark to make further improvements, such as the user can customize the location of the watermark, currently can only be displayed in the lower right corner of the thumbnail Verification code module will add custom background map function, the user can insert multiple background map as the background of the verification code, each refresh will randomly replace the background map.

  • 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.