Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Yii Application Development Cookbook - Second Edition

You're reading from   Yii Application Development Cookbook - Second Edition This book is the perfect way to add the capabilities of Yii to your PHP5 development skills. Dealing with practical solutions through real-life recipes and screenshots, it enables you to write applications more efficiently.

Arrow left icon
Product type Paperback
Published in Apr 2013
Publisher Packt
ISBN-13 9781782163107
Length 408 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (20) Chapters Close

Yii Application Development Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Under the Hood FREE CHAPTER 2. Router, Controller, and Views 3. AJAX and jQuery 4. Working with Forms 5. Testing Your Application 6. Database, Active Record, and Model Tricks 7. Using Zii Components 8. Extending Yii 9. Error Handling, Debugging, and Logging 10. Security 11. Performance Tuning 12. Using External Code 13. Deployment Index

Using exceptions


Exceptions are a core PHP feature, but they are seldom used fairly. Yii makes exceptions very useful.

There are two main areas where Yii exceptions come in handy, which are as follows:

  • Exceptions allow the simplifying of the process of detecting and fixing application errors and special situations, such as database connection failure or API failure

  • Exceptions allow the generating of different HTTP responses in a very clean way

Generally, an exception should be thrown when a component cannot handle a special situation, such as the one said earlier, and needs to leave it to higher-level components.

How to do it…

  1. Let's assume that we have an application/apis/lyrics/LyricsFinder.php class that makes an HTTP request to an API using CURL and returns lyrics for a song based on its name. This is how we can use exceptions inside of it:

    // create some custom exceptions to be able to catch them
    // specifically if needed
    
    // general lyrics finder exception
    class LyricsFinderException extends CException {}
    
    // used when there is a connection problem
    class LyricsFinderHTTPException extends LyricsFinderException{}
    
    
    class LyricsFinder
    {
       private $apiUrl = 'http://example.com/lyricsapi&songtitle=%s';
    
       function getText($songTitle)
       {
          $url = $this->getRequestUrl($songTitle);
          $curl = curl_init();       
          curl_setopt($curl, CURLOPT_URL, $url); 
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
          $result = curl_exec($curl);
    
          // if there is an HTTP error, we'll throw an // exception 
          if($result===false)
          {
             $errorText = curl_error($curl);
             curl_close($url);
             throw new LyricsFinderHTTPException($errorText);
          }
    
          curl_close($curl);
          return $result;
       }
       
       private function getRequestUrl($songTitle)
       {
          return sprintf($this->apiUrl, urlencode($songTitle));
       }
    }
  2. As we don't know how a specific application needs to handle its API connection, we will leave it to the application itself by throwing a custom exception LyricsFinderHTTPException. This is how we can handle it in our protected/controllers/TestController.php class:

    class TestController extends CController
    {
      public function actionIndex($song)
      {
        $lyric = 'Nothing was found.';
        
        // importing api class
        Yii::import('application.apis.lyrics.LyricsFinder');
    
        $finder = new LyricsFinder();
    
        if(!empty($song))
        {
           // We don't want to show user an error.
           // Instead we want to apologize and
           // invite him to try again later.
           try {
              $lyric = $finder->getText($song);
           }
           // we are looking for specific exception here
           catch (LyricsFinderHTTPException $e)
           {
              echo 'Sorry, we cannot process your request. Try again later.';
           }
        }         
    
        echo $lyric;
      }
    }
  3. Another usage of Yii exceptions is the generation of different HTTP responses by throwing CHttpException. For example, an action that displays a blog post represented by a Post model loaded by its ID will look like this:

    class PostController extends CController
    {
      function actionView()
      {
        if(!isset($_GET['id']))
          // If there is no post ID supplied, request is 
          // definitely wrong.
          // According to HTTP specification its code is 400.
          throw new CHttpException(400);
          
          // Finding a post by its ID
          $post = Post::model()->findByPk($_GET['id']);
          
          if(!$post)
             // If there is no post with ID specified we'll 
             // generate HTTP response with code 404 Not Found.
             throw new CHttpException(404);
    
             //  If everything is OK, render a post
             $this->render('post', array('model' => $post));
      }
    }

How it works…

Yii converts all non-fatal application errors to CException automatically.

Additionally, the default exception handler raises either the onError event or the onException event. The default event handler writes a log message with the error level set to error. Additionally, if your application's YII_DEBUG constant is set to true, unhandled exceptions or errors will be displayed at a handy error screen. This screen includes a call stack trace, a code area where the exception was raised, and the file and line where you can look for the code to fix.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Yii Application Development Cookbook - Second Edition
You have been reading a chapter from
Yii Application Development Cookbook - Second Edition - Second Edition
Published in: Apr 2013
Publisher: Packt
ISBN-13: 9781782163107
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Modal Close icon
Modal Close icon