Use the OOP feature of PHP to implement data protection. Read the OOP feature of PHP to implement data protection. in PHP4, variable declaration usually uses var, while in PHP5, you can use the object-oriented programming (OOP) feature to customize the visibility of data-accessibility. the visibility is very similar to the variable scope, but provides a better control mechanism, there are three types: "> <LINKhref =" http: // ww
In PHP 4, declared variables usually use var, while in PHP 5, you can use the object-oriented programming (OOP) feature to customize data visibility-accessibility, visibility is similar to the variable scope here, but provides a better control mechanism with three types of visibility modifiers:
Public (default) -- variables can be accessed or modified globally.
Protected -- variables can only be accessed or modified in the class itself and directly derived (using the extends statement) class.
Private -- variables can only be accessed or modified within the class.
Similar to interface implementation, violation of these rules in a program will lead to serious errors. Similarly, they exist purely for the convenience of programmers. However, this does not mean that you can ignore them and specify the visibility of a class member variable to protect the data in the object from external influences.
Assume there is a MySqlDB class, where a $ link variable is declared as private, which means this variable can only be accessed from the object using the $ this variable, this prevents unexpected overwriting of other objects or functions outside the class. here, we will use the visibility feature to help us create a query object.
You can regard a query as a separate entity, which can be executed and return results. Some database systems also have stored procedures. stored procedures are similar to functions. they store query statements and accept corresponding parameters during calls, however, MySQL did not provide similar functions before MySQL 5.1, and some other types of database management systems do not.
In this article, we will combine the above two features into the example query object. the example will simulate a basic stored procedure and save the result pointer internally. Currently, the focus is to execute query from an object, where you can call the query () function of the MySqlDB object.
The following public functions can be defined in the query object:
_ Construct () -- The constructor accepts a parameter that contains the instance reference that implements the DB interface object.
Prepare () -- function prepare () initializes the stored procedure of the query. It may contain one or more limited placeholders, which will be passed as parameters to the execute () function. A placeholder is defined as a colon related to the number of parameters followed by an integer and a letter related to the parameter type.
A simple query containing placeholders looks like the following:
SELECT col1, col2 FROM table_name WHERE col1 =: 1I
Execute () -- The execute () function will execute the query. If it is initialized as a stored procedure too early by the prepare () function, any passed parameters will be used as the execution parameters of the stored procedure. otherwise, the first parameter is only used as the query text. The execute () function returns the result after the query is executed.
Compile () -- The compile () function is similar to the execute () function. In fact, the query is not executed. Instead, all placeholders in the query string are replaced and the stored procedure parameters are accepted, and return the compiled query version.
Protected member
As mentioned above, the concept of visibility can be used to hide the internal work of an object and protect the data integrity required for the internal work. As explained above, the result pointer returned by the query will be saved as the protected attribute. This protects members because the query objects of specific databases derived from the query object may overload some core functions.
Deep mining code
The theory is enough. now I want to write code. First, create a template shown in Example 1:
Example 1: a template for the database query class
Class DBQuery
{
/**
* Save a reference that implements the DB interface object.
*/
Protected $ db;
/**
* If it is a stored procedure, set it to true.
*/
Protected $ stored_procedure = false;
/**
* Save a query that deletes all strings.
*/
Private $ query;
/**
* It is used to match quotation marks in SQL.
*/
Private static $ QUOTE_MATCH = "/(".*(? Db = $ db;
}
Public function prepare ($ query)
{
$ This-> stored_procedure = true;
}
Public function compile ($ args)
{}
Public function execute ($ query)
{}
}
Function prepare
For the template in example 1, the first thing you need to do is to build the prepare () function. to ensure that characters without quotation marks are accidentally parsed as placeholders, the function should remove all strings in the query and temporarily store them in a number Group. Strings themselves are also replaced by placeholders, which are often recognized as strings that should not appear in SQL statements. During the compilation of the query, the process placeholder will be replaced first, and then the string will be put back into the query. this is through the preg_replace () function, and the other is used as the preg_replace () the helper callback function of the function is complete.
Example 2: prepare () function
/**
* Prepare the query as a stored procedure.
* @ Param string $ query Prepared query text
* @ Return void
*/
Public function prepare ($ query)
{
$ This-> stored_procedure = true;
$ This-> quote_store = array (); // clear quotation marks
$ This-> query = preg_replace (self: $ QUOTE_MATCH, '$ this-> SQL _quote_replace ("1 "? "1": '2') ', $ query );
}
Private function SQL _quote_replace ($ match)
{
$ Number = count ($ this-> query_strings );
$ This-> query_strings [] = $ match;
Return "$ | $ number ";
}
Pay attention to the use of the static QUOTE_MATCH attribute private, as well as the quote_store attribute and SQL _quote_replace () function. Compared with protected, this definition of private makes sure that any subclass of the prepare () method of the overloaded query class uses its own mechanism to remove quotation marks.
Function compile
The next step is to build the compile () and execute () functions.
The compile () function is shown in Example 3. the function is as follows:
· The number of accepted parameters is variable (that is, variable parameters), which matches the placeholders in the query.
· Check whether the placeholder is of the correct data type and replace it with the value in the parameter.
· Return a query as a string without executing it.
· If the query object is not initialized as a stored procedure using the prepare () function, an exception is thrown.
Example 3: compile () function
/**
* The compiled query is returned, but it is not executed.
* @ Param mixed $ args,... Query Parameters
* @ Return string Compiled Query
*/
Public function compile ($ params)
{
If (! $ This-> stored_procedure ){
Throw new Exception ("the stored procedure is not initialized! ");
}
/* Alternative parameter */
$ Params = func_get_args (); // Obtain function parameters
$ Query = preg_replace ("/(? Query );
Return $ this-> add_strings ($ query); // put the string back in the query
}
/**
* Re-insert the string removed by the prepare () function.
*/
Private function add_strings ($ string)
{
$ Numbers = array_keys ($ this-> query_strings );
$ Count = count ($ numbers );
$ Searches = array ();
For ($ x = 0; $ x <$ count; $ x ++ ){
$ Searches [$ x] = "$ | $ {$ numbers [$ x]}";
}
Return str_replace ($ searches, $ this-> query_strings, $ string );
}
/**
* A placeholder is replaced during each execution.
*/
Protected function compile_callback ($ params, $ index, $ type)
{
-- $ Index;
/* Throw an exception */
If (! Isset ($ params [$ index]) {
Throw new Exception ("The number of parameters not received by the stored procedure! ");
}
/* You can add other types here, such as date and time. */
Switch ($ type ){
Case's ':
Return '"'. $ this-> db-> escape_string ($ params [$ index]). '"';
Break;
Case 'I ':
Return (int) $ params [$ index];
Break;
Case 'n ':
Return (float) $ params [$ index];
Default:
Throw new Exception ("The specified data type '$ type' in the stored procedure cannot be identified. ");
}
}
The compile_callback () function uses two additional functions. the compile_callback () function is used as a callback function in the preg_replace () function call. each time a placeholder is found in the query, and replace it with the value passed to the compile function.
Execute function
Finally, you also need to build the execute () function, execute () function to compile the query and execute it using the DB object, where the DB object is used to initialize the DBQuery object. Note how to use the call_user_func_array () function in example 4 to obtain the compiled query. the reason for this is that the function execute () is not running until it is run, to determine the number of parameters passed to it.
Example 4: execute () function
/**
*
* Execute the current query and replace the placeholder with the provided parameters.
*
* @ Param mixed $ queryParams,... Query parameter
* @ Return resource A reference to the resource representing the executed query.
*/
Public function execute ($ queryParams = '')
{
// Example: SELECT * FROM table WHERE name =: 1 s and type =: 2I AND level =: 3N
$ Args = func_get_args ();
If ($ this-> stored_procedure ){
/* Call the compile function to obtain the query */
$ Query = call_user_func_array (array ($ this, 'compile '), $ args );
} Else {
/* If the stored procedure is not initialized, it is executed as a standard query. */
$ Query = $ queryParams;
}
$ This-> result = $ this-> db-> query ($ query );
Return $ this-> result;
}
Integrate all
To demonstrate how to use a query object, a small example is constructed below. it uses the DBQuery object as a stored procedure and checks whether the correct user name and password are entered. see example 5:
Example 5:
Require 'MySQL _ db. php5 ';
Require_once 'query2. php5 ';
$ Db = new MySqlDb;
$ Db-> connect ('host', 'username', 'pass ');
$ Db-> query ('use content_management_system ');
$ Query = new DBQuery ($ db );
$ Query-> prepare ('select fname, sname FROM users WHERE username =: 1 s and pword =: 2 s and expire_time <: 3i ');
If ($ result = $ query-> execute ("visualad", "apron", time ())){
If ($ db-> num_rows ($ result) = 1 ){
Echo ('The credential is correct. ');
} Else {
Echo ('The credential is incorrect and the session has expired. ');
}
} Else {
Echo ('query execution error: '. $ db-> error ());
}
In this article, you have learned how to use access modifiers private, protected, and public to protect data and restrict data object visibility when declaring class variables. in PHP 5, these concepts can also be used in other data classes to protect their important internal data.