Book Image

Yii 1.1 Application Development Cookbook

Book Image

Yii 1.1 Application Development Cookbook

Overview of this book

When Alex told me he was about to write a Yii cookbook about a year ago, I was wondering how original it would be, considering the fact that there was already an online user-contributed cookbook (aka. Yii wiki). It turned out Alex produced a book that is not only full of wisdom about how to use Yii effectively, but also presented in such a systematic way that it can be taken as an essential companion book to the definitive guide to Yii. In fact, Alex has successfully intrigued the interest of every member in the Yii developer team when he asked for review and comments on his newly finished book chapters.As the founder and the lead developer of the Yii framework, I feel this book is a must-read for every Yii programmer. While this book does not describe directly the rules set by Yii, it shows how to program with Yii from a practical perspective. People who are driven by tight project schedules will find this book very handy as it gives ready-to-use solutions to many problems they may face in their projects; people who are already familiar with Yii will also find this book very informative as most problem solutions given in the book can be considered as officially recommended because they have undergone thorough review of every Yii developer team member. Alex, through this book and his active participation in the Yii project, proved himself to be a great programmer as well as a good writer. Qiang XueLead developer of the Yii framework Yii framework is a rapidly growing PHP5 MVC framework often referred to as Rails for PHP. It has become a solid base for many exciting web applications such as Stay.com and Russia Today's meetfriends.rt.com and can be a good base for your developments. Yii is an object-oriented, high-performance, component-based PHP web application framework. Yii is pronounced as Yee and is an acronym for "Yes It Is!". Familiar with Yii and want to exploit it to its full potential, but do not know how to go about it? Yii 1.1 Application Development Cookbook will show you how to use Yii efficiently. You will learn about implementing shortcuts using core features, creating your own reusable code base, using test-driven development, and many more topics that will escalate your knowledge in no time at all! Yii 1.1 Application Development Cookbook will help you learn more about Yii framework and application development practices in general with demonstrations of shortcuts and information about dangerous things you should not do. Grouped in 13 chapters, the recipes will assist you to write your applications exploiting Yii core functionality to its full potential. The chapters are generally independent of each other and you can start reading from the chapter you need most, whether it is "AJAX and jQuery", "Database, Active Record and Model Tricks" or "Extending Yii". The most interesting topics include Yii application deployment, a guide to writing your own extensions, advanced error handling, debugging and logging, application security, and performance tuning. Yii 1.1 Application Development Cookbook will help you utilize Yii functionalities completely and efficiently.
Table of Contents (21 chapters)
Yii 1.1 Application Development Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Working with request


You can work with request data directly using PHP superglobals such as $_SERVER, $_GET, or $_POST but the better way is to use Yii 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, returned parts are marked with a bold font.

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 request type are getIsPostRequest, getIsAjaxRequest , and getRequestType.

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

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

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

  • While PHP provides superglobals for both POST and GET, Yii way 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 DB
          $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 to initiate 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. Mimetype, 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!!');
   }
}