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

Working with requests


You can work with request data directly using PHP superglobals such as $_SERVER, $_GET, or $_POST but the better way is to use Yii's powerful CHttpRequest class that resolves inconsistencies among different web servers, manages cookies, provides some additional security, and has a nice set of OO methods.

How to do it…

You can access the request component in your web application by using Yii::app()->getRequest(). So, let's review the most useful methods and their usage, methods that return different parts of the current URL. In the following table, the returned parts are marked with a bold font.

Methods

Results

getUrl

http://cookbook.local/test/index?var=val

getHostInfo

http://cookbook.local/test/index?var=val

getPathInfo

http://cookbook.local/test/index?var=val

getRequestUri

http://cookbook.local/test/index?var=val

getQueryString

http://cookbook.local/test/index?var=val

The methods that allow us to ensure the request types are getIsPostRequest, getIsAjaxRequest , and getRequestType .

  • For example, we can use getIsAjaxRequest to serve different content based on the request type:

    class TestController extends CController
    {
       public function actionIndex()
       {
          if(Yii::app()->request->isAjaxRequest)
             $this->renderPartial('test');
          else
             $this->render('test');
       }
    }

    In the preceding code, we are rendering a view without a layout if the request is made through AJAX.

  • While PHP provides superglobals for both POST and GET, Yii allows us to omit some additional checks:

    class TestController extends CController
    {
       public function actionIndex()
       {
          $request = Yii::app()->request;
    
          $param = $request->getParam('id', 1);
          // equals to
          $param = isset($_REQUEST['id']) ? $_REQUEST['id'] : 1;
    
          $param = $request->getQuery('id');
          // equals to
          $param = isset($_GET['id']) ? $_GET['id'] : null;
    
          $param = $request->getPost('id', 1);
          // equals to
          $param = isset($_POST['id']) ? $_POST['id'] : 1;
       }
    }
  • getPreferredLanguage tries to determine the user's preferred language. It can't be completely accurate, but it is good to use it as a fallback in case the user has not specified a preferred language manually.

    class TestController extends CController
    {
       public function actionIndex()
       {
          $request = Yii::app()->request;
          $lang = $request->preferredLanguage;
    
          // Trying to get language setting from 
          // Settings table that holds id of the user,
          // setting name and setting value.
          $criteria = new CDbCriteria();
          $criteria->compare('user_id', $request->getQuery('userid'));
          $criteria->compare('key', 'language');
          $setting = Settings::model()->find($criteria);
          if($setting)
             $lang = $setting->value;
    
          Yii::app()->setLanguage($lang);
          
          echo Yii::t('app', 'Language is: ').$lang;
       }
    }
  • sendFile allows us to initiate a file download as follows:

    class TestController extends CController
    {
       public function actionIndex()
       {
       $request = Yii::app()->getRequest();
          $request->sendFile('test.txt', 'File content goes here.');
       }
    }

    This action will trigger a file download and send all necessary headers, including content type (mimetype) and content length. The MIME type, if not set manually as a third parameter, will be guessed based on the filename's extension.

  • The last thing we are going to show in this chapter is the getCookies method. It returns a CCookieCollection class instance that allows us to work with cookies. As CCookieCollection extends CMap, we can use some native PHP methods as follows:

    class TestController extends CController
    {
       public function actionIndex()
       {
          $request = Yii::app()->request;
          // getting a cookie
          $cookie = $request->cookies['test'];
          if($cookie)
             // printing cookie value
             echo $cookie->value;      
          else {
             // creating new cookie
             $cookie=new CHttpCookie('test','I am a cookie!');
             $request->cookies['test'] = $cookie;
          }
    }

There's more...

If you are working with a lot of cookie values and want to shorten the code provided, then you can use a helper as follows:

class Cookie
{
  public static function get($name)
  {
       $cookie=Yii::app()->request->cookies[$name];
       if(!$cookie)
           return null;

       return $cookie->value;
  }

  public static function set($name, $value, $expiration=0)
  {
       $cookie=new CHttpCookie($name,$value);
       $cookie->expire = $expiration;
       Yii::app()->request->cookies[$name]=$cookie;
  }
}

After you drop this code into protected/components/Cookie.php, you will be able to perform the following:

class TestController extends CController
{
   public function actionIndex()
   {
      $cookie = Cookie::get('test');
      if($cookie)
         echo $cookie;      
      else
         Cookie::set('test','I am a cookie!!');
   }
}
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 ₹800/month. Cancel anytime
Modal Close icon
Modal Close icon