Proxy and exception customization in PHP5 OOP Programming

Source: Internet
Author: User

1. DBQuery object

Now, our DBQuery object simply imitates a stored procedure-Once executed, it returns a result resource that must be saved; and if you want to use functions in 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 (which is designed to operate on a query execution result? Let's continue to use the code in the previous example. Let's assume that the DBQuery object manages our result resources. The source code of the DBQuery class is shown in List 1.

List 1. Use 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 (Incorrect Credentials/Session Expired );
}
} Catch (QueryException $ e ){
Echo (Error executing query:. $ e );
}

In the Code modified 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 the details of the error.

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

Therefore, you need to modify the DBQuery object to include all the functions-they operate on a result resource from the DB object. When you execute a query to call the corresponding function of the DB object and return its results, you need to use the stored results. The following functions will be added:

List 2: Use a proxy to expand 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 executed, and then proxies the task to the DB object, returning the result 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, which 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 use the type check function (is_a () provided in PHP ()). Now, you can simply forcibly convert the object type by adding the type name before the function parameter. You have seen the type prompt from our DBQuery object to ensure that an object implementing the DB interface is passed to the object constructor.

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

When you use the type prompt, 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 caught an exception called QueryException (We will implement this object later. An exception is similar to an error, but it is more general. The best way to describe an exception is to use emergency. Although an emergency can not be "Fatal", it must be handled. When an exception is thrown in PHP, the current execution range is quickly terminated, whether it is a function, try .. catch Block or the script itself. Then, the exception traverses the call stack-terminates each execution range until or in a try .. catch Block capture it or it reaches the top of the Call Stack-at this time it generates a fatal error.

Exception Handling is another new feature in PHP 5. When 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 execution from the next line of the Code where the exception is 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.

/**
* Execute the current query
*
* Execute the current query-replace any point operator with the provided parameters
*.
*
* @ Parameter: mixed $ queryParams,... query parameter
* @ Return: Resource A-The resource that executes the query according to the description.
*/
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 standard query */
$ Query = $ queryParams;
}
$ Result = $ this-> db-> query ($ query );
If (! $ Result ){
Throw new QueryException ($ this );

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.