PHP5 _php tutorial on agent and exception customization in OOP programming

Source: Internet
Author: User
First, Dbquery object

Now, our Dbquery object simply mimics a stored procedure-once executed, returns a result resource that must be saved, and if you want to use a function on that result set (such as num_rows () or Fetch_row ()), you must pass the MySQLdb object. So what happens if the Dbquery object implements the MySQLdb object, which is designed to operate on a result of executing a query? Let's continue using the code from the previous example, and let's assume that our result resources are now managed by the Dbquery object. The source code for the Dbquery class is shown in Listing 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=:1s and Pword=:2s 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 modified code above, we are most interested in the catch statement and the EXECUTE statement.

· The EXECUTE statement no longer returns a result resource, and now it returns the Dbquery object itself.

· The Dbquery object now implements the Num_rows () function-we are already familiar with the DB interface.

· If the query execution fails, it throws an exception of type queryexception. When converted to a string, it returns details about the error that occurred.

To do this, you need to use a proxy. In fact, you have used the proxy in our Dbquery object, but now we will use it more deeply to bind it tightly to the MySQLdb object. The Dbquery object has been initialized with an object that implements the DB interface, and it already contains a member function execute-the query () method that calls the DB object to execute it. The Dbquery object itself does not actually query the database, which is done by the DB object. This is the proxy, which is actually a process-with this process, an object can implement a particular behavior by sending the message to another object that implements the same or similar behavior.

To do this, you need to modify the Dbquery object to include all the functions-they manipulate a result resource from the DB object. When you execute a query to invoke the corresponding function of the DB object and return its results, you need to use the stored results. The following functions are added:

Listing 2: Extending the Dbquery class with a proxy.

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 fairly straightforward. It first checks to make sure that the query has been executed and then proxies the task to the DB object, returning it as if it were the query object itself (called a basic database function).

   second, type hint (type Hinting)

In order for the agent to work, we need to make sure that the $db variable of the Dbquery object is an instance of the object that implements the DB interface. Type hints are a new feature in PHP 5 that enables you to cast function arguments to specific types of objects. Before PHP 5, the only way to ensure that a function parameter was a specific object type was to use the type-checking function provided in PHP (also known as is_a ()). Now you can simply cast the object type-by adding the type name before the function argument. You've seen the type hints from our Dbquery object, which ensures that an object that implements the DB interface is passed to the object constructor.

Public function __construct (DB $db)
{
$this->db = $db;
}

When using type hints, you can specify not only the object type, but also abstract classes and interfaces.

   c. Throw an exception

You may have noticed from the above code that you are capturing an exception called queryexception (which we will implement later in this object). An exception is similar to an error, but it is more generic. The best way to describe an exception is to use emergency. Although a emergency can not be "deadly", it must be handled. When an exception is thrown in PHP, the current scope of execution is quickly terminated, regardless of whether it is a function, try: The catch block is also the script itself. The exception then iterates through the call stack-terminating each execution range until either a try: Catch block or it arrives at the top of the call stack-it will generate a fatal error.

Exception handling is another new feature in PHP 5 that enables good control of error handling and reporting when associated with OOP. A try: Catch blocks are an important mechanism for handling exceptions. Once captured, the script resumes execution from the next line of code that the exception was 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-the Dbquery object that caused the error is passed to it.

List 3. Throws an exception.

/**
* Execute Current Query
*
* Execute current query-replace any point character with the supplied parameter
* .
*
* @ parameter: Mixed $queryParams, ... Query parameters
* @ return: Resource A-reference describes the resource that executes the query.
*/
Public Function Execute ($queryParams =)
{
Example: SELECT * from table WHERE name=:1s and Type=:2i and level=:3n
$args = Func_get_args ();
if ($this->stored_procedure) {
/* Call the Compile function to get the query */
$query = Call_user_func_array (Array ($this, compile), $args);
} else {
/* A stored procedure is not initialized, so it is executed as a standard query */
$query = $queryParams;
}
$result = $this->db->query ($query);
if (! $result) {
throw new Queryexception ($this);

http://www.bkjia.com/PHPjc/508484.html www.bkjia.com true http://www.bkjia.com/PHPjc/508484.html techarticle Dbquery Object Now, our Dbquery object simply mimics a stored procedure that, once executed, returns a result resource that must be saved, and if you want to use the knot ...

  • Related Article

    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.