Build Your own PHP Framework (iii)

Source: Internet
Author: User
Tags finally block php framework try catch

Continuation of the statement

Then improve your PHP framework, the main content of this update is:

    • The mechanism of exception handling is introduced
    • Improved exception and error handling
    • Mapping data tables to model classes
Exception handling

Exception handling: Exception handling is a mechanism in a programming language or computer hardware that handles anomalies in software or information systems (i.e., certain special conditions that are beyond the normal execution of a program)

Exception handling is used to handle the exception condition in the program, although the "abnormal state", but still in the program writer's expected, in fact, the program's exception handling can be replaced by the ' if Else ' statement, but exception handling naturally has its advantages.

The individual summarizes its advantages as follows:

    • You can quickly terminate the process, reset the system state, clean up variables and memory consumption, and in a normal Web application, fast CGI cleans up variables and contexts automatically after a single request is completed, but it can be handy if you execute a daemon script in PHP's command-line mode.
    • A large number of if else statements can make the code difficult to understand, using exception handling to make the program logic clearer, after all, the entry for handling exceptions is only a catch statement.
    • The function in a volume program has an abnormal result or condition, if the return method of the function returns the exception information, layers upward, each time to make a return judgment. Using exception handling we can assume that all return information is normal and avoids a lot of code duplication.

While putting code in a try catch block can be slightly inefficient, it is less expensive than the advantages. So how do you use exception handling in PHP?

PHP has a built-in exception class that allows us to throw exceptions by instantiating exception classes. We put the code in a try statement and then use catch to try to catch the exception thrown in the try code block and handle the exception. We can also use the finally statement block after the catch snippet, whether or not an exception will execute the code of the finally code block, as in the following code:

try{    throw new Exeption(‘msg‘[,‘code‘,$previous_exeception]);}catch(Exeption $var) {    process($var);}catch(MyException $e){    process($e)}finally{    dosomething();}

With the try Catch statement, you need to be aware that:

    • When we throw an exception, we instantiate an exception class, which can be defined by itself, but in a catch statement, we need to specify the class name of the exception object to be captured, and only the exception object of the particular class is captured. Of course, we can catch an exception base class (PHP built-in exception class) at the end to ensure that exceptions can be caught.
    • When an exception is thrown, the program is terminated, and the backtracking code finds the first catch statement that captures it, and the try Catch statement can be nested, and the CACTH statement, as shown in the preceding code, can be defined more than once.
    • The finally block executes after the try catch block finishes, even if you return using return in the Try Catch block, the program is not executed to the last.
Exception handling in the framework

Having said so much about the anomaly (and of course explaining it to understand and use the framework), how does it work in the framework?

Overriding exception classes

We can rewrite the exception class to refine its internal methods:

<?php  class Exception  {      protected $message = ‘Unknown exception‘;   // 异常信息      protected $code = 0;                        // 异常代码      protected $file;                            // 发生异常的文件名      protected $line;                            // 发生异常的代码行号      function __construct($message = null, $code = null,$previous_exeception = null);      final function getMessage();                // 返回异常信息      final function getCode();                   // 返回异常代码      final function getFile();                   // 返回发生异常的文件名      final function getLine();                   // 返回发生异常的代码行号      final function getTrace();                  // 返回异常trace数组      final function getTraceAsString();          // 返回异常trace信息    /**     * 记录错误日志     */    protected function log(){        Logger::debug();    }}  

As above, the final method cannot be overridden, except that we can define our own methods, such as logging exception logs, like my custom log method, which can be used directly in the catch code block to $e->log record an exception log.

Registering Global Exception methods

We can use Set_exception_handler (' Exceptionhandler ') to globally capture an exception that is not caught by a catch block, and this exception handler needs to pass in an exception handling object to parse this exception handling information. Avoids the system to appear the non-humanized prompt, enhances the frame robustness.

function exceptionHandler($e) {    echo ‘有未被捕获的异常,在‘ . $e->getFile() . "的" . $e->getLine() . "行!";}
Other global functions

By the way, other global processing functions:

    • Set_shutdown_function (' Shutdownhandler ') to execute the function at the end of the script, which is called automatically even after the error has ended.
    • Set_error_handler (' ErrorHandler ') is called automatically when an error occurs in PHP, note that an error must be made before the error function is registered. function parameters should be ($errno, $errstr, $errfile, $errline);

Note, however, that these global functions need to be re-registered before the code snippet has been defined.

ActiveRecord Mapping of data tables and model classes

First use YII2 Activcerecord class feel good convenient, only need to define its field with the same name property and then call the Save method OK (good magic AH), it is how to achieve it, read the next source, understand its approximate implementation process (base class).

    1. Use ' describe table_name ' query statement;
    2. Parse Query results: field (field name), type (data type), null (NULL), key (index information, ' PRI ' for primary key), default (Defaults), Extra (additional information, such as auto_increment) for each of the fields
    3. By judging its primary key ( $row[‘KEY‘] == ‘PRI‘ ) information, it is saved to see if there is primary key information, if it exists, it is updated; not present, insert.
    4. In addition, the parsed field information has more magical ~ ~
Conclusion

Feel for a long time not to write a blog, ' graduation ' for a similar to the study of the professional way of people is a bit cumbersome, save the school's nostalgia, continue to set off.

Really the more study more feel that they do not know enough, in the view of some PHP framework source code, sometimes feel that they are still very far away, the sense of the overall feeling and layout, estimated the need for time and experience accumulation bar.

Because the application of the framework and their own current working relationship is not particularly large, and I have recently struggled to learn some of the programming of the underlying class of things, so the framework series may be some ' constipation ', will write some other ... These two days are ready to change places to live, run to see the House, forgive me ' short ' point.

Haha, welcome to continue to follow my blog, ah, has been in the heart.

Build Your own PHP Framework (iii)

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.