Proxy and exception customization in PHP5 & nbsp; OOP programming ||| PHP5 & nbsp; OO

Source: Internet
Author: User
1. DBQuery objects at present, our DBQuery objects simply mimic a stored procedure-once executed, a result resource that must be retained is returned; and if you want to apply the functions in the result set (such as num_rows () or fetch_row () 1. DBQuery object

Now, our DBQuery object simply imitates a stored procedure-once executed, it returns a result resource that must be retained; and if you want to apply the functions on the result set (such as num_rows () or fetch_row (), you must pass the MySqlDB object. So what if the DBQuery object is used to implement the function of MySqlDB object (its design goal is to control the result of performing a query? Let's continue to apply the code in the previous example, and let's assume that the DBQuery object now manages our results resources. The source code of the DBQuery class is shown in list 1.

List 1. apply the DBQuery class.

Require 'MySQL _ db. php ';
Require_once 'query. php ';
$ 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 ');
Try {
If ($ query-> execute ('visualad', 'apron ', time ()-> num_rows () = 1 ){
Echo ('correct credentials ');
} Else {
Echo ('encrect Credentials/Session expired ');
}
} Catch (QueryException $ e ){
Echo ('error executing query: '. $ e );
}

In the code corrected above, we are most interested in catch and execute statements.

· The execute statement no longer returns a result resource. now it returns the DBQuery object itself.

· The DBQuery object now implements the num_rows () function-we are familiar with it from the DB interface.

· If the query fails, it throws a QueryException type exception. When converted into a string, it returns detailed information about the error.

Therefore, you need an application proxy. In fact, you have already applied the proxy in our DBQuery object, but now you will apply it more deeply to closely bind it to the MySqlDB object. This DBQuery object has been initialized by an object implementing the DB interface, and it already contains a member function execute-it calls the query () method of the DB object to perform this query. This DBQuery object does not actually query the database. it submits this task to the DB object. This is the proxy. it is really a process-by sending messages to another object that implements similar or similar actions, one object can implement a special action.

To this end, you need to modify the DBQuery object to include all the functions-they hold a result resource from the DB object. When performing a query to call the corresponding function of the DB object and return its results, you need to apply the stored results. The following functions will be added:

List 2: The Application Proxy expands the DBQuery class.

Class DBQuery
{
.....

Public function fetch_array ()
{
If (! Is_resource ($ this-> result )){
Throw new Exception ('query not executed .');
}

Return $ this-> db-> fetch_array ($ this-> result );
}

Public function fetch_row ()
{
If (! Is_resource ($ this-> result )){
Throw new Exception ('query not executed .');
}

Return $ this-> db-> fetch_row ($ this-> result );
}

Public function fetch_assoc ()
{
If (! Is_resource ($ this-> result )){
Throw new Exception ('query not executed .');
}

Return $ this-> db-> fetch_assoc ($ this-> result );
}

Public function fetch_object ()
{
If (! Is_resource ($ this-> result )){
Throw new Exception ('query not executed .');
}

Return $ this-> db-> fetch_object ($ this-> result );
}

Public function num_rows ()
{
If (! Is_resource ($ this-> result )){
Throw new Exception ('query not executed .');
}

Return $ this-> db-> num_rows ($ this-> result );
}
}

The implementation of each function is quite simple. It first checks to ensure that the query has been performed, and then proxies the task to the DB object, returning its results as if it was a query object itself (called a basic database function.

   II. Type Hinting)

To enable the proxy to work, we need to ensure that the $ db variable of the DBQuery object is an instance of the object that implements the DB interface. The type prompt is a new feature in PHP 5. it enables you to forcibly convert function parameters to specific types of objects. Before PHP 5, the only way to ensure that the function parameter is a specific object type is to apply the type check function (is_a () provided in PHP ()). Now, you can simply force the type of the conversion object-by adding the type name before the function parameter. You have seen the type prompt from our DBQuery object, so that an object implementing the DB interface can be passed to the object configurator.

Public function _ construct (DB $ db)
{
$ This-> db = $ db;
}

When the application type prompts, you can not only specify the object type, but also specify the abstract class and interface.

   III. throw an exception

You may have noticed from the code above that you are capturing an exception called QueryException (which we will implement later. An exception is similar to an error, but it is more general. The best way to describe an exception is to apply emergency. Although an emergency can not be "fatal", it must be handled. When an exception is thrown in PHP, the fulfillment determines that the current category is quickly terminated, whether it is a function, try .. catch block or the script itself. Then, the exception traverses the call stack-terminate each fulfillment category until or in a try .. catch block captures it or it reaches the top of the call stack-at this point it will generate a fatal error.

Exception handling is another new feature in PHP 5. when it is associated with OOP, it can implement good control over error handling and reporting. A try... catch block is an important mechanism for handling exceptions. Once captured, the script continues to be executed from the next line of the code where exceptions are captured and processed.

If the query fails, you need to change your execute function to throw an exception. You will throw a custom exception object called QueryException-causing the wrong DBQuery object to be passed to it.

List 3. an exception is thrown.

/**
* Perform the current query
*
* Perform the current query-replace any point operator with supplied parameters
*.
*
* @ Parameter: mixed $ queryParams,... query parameter
* @ Return: Resource A-refer to the description of the resource to perform the 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 for query */
$ Query = call_user_func_array (array ($ this, 'compile '), $ args );
} Else {
/* A stored procedure is not initialized. Therefore, it is executed as a scale query */
$ Query = $ queryParams;
}
$ Result = $ this-> db-> query ($ query );
If (! $ Result ){
Throw new QueryException ($ this );
}
$ This-> result = $ result;
/* Pay attention to how we return the object itself, which enables us to call the member function from the result returned by this function.
*/
Return $ this;
}
  [1] [2] [3] Next page 

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.