PHP Exception Handling Methods

Source: Internet
Author: User
Tags spl php exception handling zend framework
This article mainly introduces some methods of exception handling in PHP. Although PHP is not a good language, its related technologies are still being improved, for more information, see

This article mainly introduces some methods of exception handling in PHP. Although PHP is not a good language, its related technologies are still being improved, for more information, see

Every new function is added to the PHP runtime to create an exponential random number. In this way, developers can use and even abuse this new feature. However, developers did not reach a consensus until there were some good and bad use cases. As these new cases emerge, we can finally identify what is the best or the worst.

Exception Handling is indeed not a new feature in PHP anyway. However, in this article, we will discuss two new features of exception handling in PHP 5.3. The first is nested exceptions. The second is a new exception type of SPL (a core extension of the current PHP Operating Mechanism) extension. These two new features can be found in this book best practices worthy of further research.


Note: Some of these features already exist in PHP versions earlier than 5.3, or at least can be implemented in PHP versions earlier than 5.3. when PHP 5.3 is mentioned in this article, it is not the PHP runtime version that is strictly responsible. on the contrary, it means that the code library and project adopt PHP 5.3 as the lowest version, but it also shows all the best practices in the new development phase. this development phase highlights the "2.0" attempts made by specific projects such as Zend Framework, Symfony, Doctrine, and PEAR.

Background

PHP 5.2 has only one Exception class Exception. According to the Zend Framework/PEAR development standard, this class is the base class of all Exception classes in your library. If you create a library named MyCompany, all the code files in the library will start with MyCompany _ according to the Zend Framework/PEAR standard. If you want to create your own Exception base class: MyCompany_Exception for the database, use this class to inherit the Exception, and then inherit and throw the Exception class from the component. For example, if you have a component MyCompany_Foo, you can create an exception base class MyCompany_Foo_Exception for the component. These exceptions can be caught by codes that capture MyCompany_Foo_Exception, MyCompany_Exception, or Exception. For other code in the library that uses this component, this is a layer-3 exception (or more, depending on the number of child classes of MyCompany_Foo_Exception). They can handle these exceptions as needed.


In php5, basic exception classes support nested features. What is nesting? Nesting is a capability that can capture special exceptions or catch a new exception object created with reference to the original exceptions. This will allow the caller attribute to be reflected in the two exception classes in the more open overhead library, and of course it will also be reflected in the exception classes with the original exception behavior.

Why are these features very useful? Generally, it is the most effective code to throw exceptions of its own type by using other code. The code may be code of a third-party code library that encapsulates some adaptive functions using the adapter mode, or a simple code that throws exceptions using some PHP extensions.


For example, in component Zend_Db, it uses the adapter mode to encapsulate specific PHP extensions to create a database abstraction layer. in an adapter, Zend_Db encapsulates PDO, and PDO throws its own exception PDOException. Zend_Db needs to capture these PDO-specific exceptions, and let them be thrown again with the expected and known type Zend_Db_Exception. this ensures that Zend_Db will always throw exceptions of the Zend_Db_Exception type (so they can be captured), and they can also access the PDOException thrown at the very beginning as needed.

The following example shows how a fictitious database adapter can implement embedded exceptions:

Class MyCompany_Database {/*** @ var PDO object setup during construction */protected $ _ pdoResource = null; /*** @ throws MyCompany_Database_Exception * @ return int */public function executeQuery ($ SQL) {try {$ numRows = $ this-> _ pdoResource-> exec ($ SQL);} catch (PDOException $ e) {throw new MyCompany_Database_Exception ('query was unexecutable', null, $ e) ;}return $ numRows ;}}

To use an embedded exception, you must call the getPrevious () method of the caught exception:

// $ SQL and $ connectionParameters assumedtry {$ db = new MyCompany_Database ('pdo', $ connectionParams); $ db-> executeQuery ($ SQL);} catch (MyCompany_Database_Exception $ e) {echo 'General Error :'. $ e-> getMessage (). "\ n"; $ pdoException = $ e-> getPrevious (); echo 'pdo Specific error :'. $ pdoException-> getMessage (). "\ n ";}

Most recently implemented PHP extensions have OO (Object-Oriented) interfaces. Therefore, these Apis tend to throw exceptions rather than terminating errors. Extensions that can throw exceptions in PHP Include PDO, DOM, Mysqli, Phar, Soap, and SQLite.

New Feature: new core exception type

In PHP 5.3 development, we showed some interesting new exception types. These exceptions already exist in PHP 5.2.x, but they have not recently come to the "reevaluate" Best Practices, and now they are even more eye-catching. They applied the SPL extensions and listed in the Manual (here) because these new exception types are part of the PHP core and part of the SPL, they can be used by anyone who uses PHP 5.3 (or above) to run code. Although it does not seem so important when writing code at the application layer, it is even more important to use these new exception types when we write or use code libraries.


So why is the new exception of the normal type? In the past, developers tried to add more content to the exception message to give the exception more meaning. Although this is feasible, it has several disadvantages. First, you cannot capture message-based exceptions. This is a problem. If you know that a group of codes are of the same exception type and different prompt messages correspond to different exceptions, the processing will be quite difficult. For example, for an authentication class, in $ auth-> authenticate (); It throws the same type of exception (assuming it is an exception), but different messages correspond to two specific faults: the cause of the failure is that the authentication server cannot reach the same exception type, but the verification message indicating the failure is different. In this case (note that using exceptions may not be the best way to handle authentication responses), this will require the use of strings to parse messages to process these two different situations.

The solution to this problem is obviously to encode the exception in some way, so that it is easier to query when you need to identify how to respond to this abnormal environment. The first response library uses the $ code attribute of the exception base class. The other is to create a subclass or a new exception class that can be thrown and can describe its own behavior. These two methods have the same obvious disadvantages. Neither of them presents the best example. Neither of them is considered a standard, so every project that tries to replicate the two solutions will have minor changes, this forces the use to go back to the document to understand the specific solutions already in the created library. Now, by using the new SPL type method, also known as the php standard library, developers can use the same method in their projects, and new best methods for reusing these projects have emerged.

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.