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

Using import and autoloading


When programming with PHP, one of the most annoying things is loading additional code with include and require. Fortunately, you can do it automatically using the SPL class loader (http://php.net/manual/en/function.spl-autoload.php).

Autoloading is one of the features which Yii relies on. Still, there are many questions about it on the forums. Let's get it clear and show how we can use it.

When we are using a class, for example, CDbCriteria, we are not including it explicitly so PHP initially cannot find it and is trying to rely on the autoloading feature; SPL autoloader to be precise. In most cases, Yii default autoloader (YiiBase::autoload) will be used.

For the sake of speed and simplicity, almost all core framework classes are loaded when needed without including or importing them explicitly. It's done through YiiBase::$_coreClasses map, so loading core classes is very fast. Zii classes, such as CMenu, extension classes or your own classes are not loaded automatically, so we need to import them first.

To import classes, we will use Yii::import:

  • Import does not include a class immediately by default

  • It does not include a class if it is not used

  • It will not load a class twice, so it is safe to import the same class multiple times

How to do it...

  1. Let's assume that we have a custom class named LyricsFinder that finds lyrics for a given song. We have put it under protected/apis/lyrics/ and in our protected/controllers/TestController.php, we are trying to use it in the following way:

    class TestController extends CController
    {
       public function actionIndex($song)
       {
          $lyric = 'Nothing was found.';
          $finder = new LyricsFinder();
    
          if(!empty($song))
             $lyric = $finder->getText($song);
    
          echo $lyric;
       }
    }
  2. When executing it, we will get the following PHP error:

    include(LyricsFinder.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory.
  3. Yii helps us there a bit because at the error screen, we can see that autoloader fails because it doesn't know where to look for our class. Therefore, let's modify our code:

    class TestController extends CController
    {
       public function actionIndex($song)
       {
          $lyric = 'Nothing was found.';
          
          // importing a class
          Yii::import('application.apis.lyrics.LyricsFinder');
    
          $finder = new LyricsFinder();
    
          if(!empty($song))
             $lyric = $finder->getText($song);
    
          echo $lyric;
       }
    }

    Now our code works.

    Note

    The built-in Yii class loader requires that each class should be placed into a separate file named the same as the class itself.

How it works...

Let's look at application.apis.lyrics.LyricsFinder:

application is a standard alias that points to your application protected folder and is translated into a filesystem path. The following table shows some more standard aliases:

Alias

Path

application

path_to_webroot/protected

system

path_to_webroot/framework

zii

path_to_webroot/framework/zii

webroot

path_to_webroot

ext

path_to_webroot/protected/extensions

Note

You can define your own aliases using the Yii::setPathOfAlias method. Typically, it can be done as the first lines of protected/config/main.php, so all other config parts will be able to use these new aliases.

apis.lyrics are translated to apis/lyrics and are appended to a path retrieved from the application alias, and LyricsFinder is the class name we want to import.

If LyricsFinder requires some additional classes located in its directory, then we can use Yii::import('application.apis.lyrics.*') to import the whole directory. Note that * does not include subfolders, so if you need lyrics/includes, you should add another import statement Yii::import('application.apis.lyrics.includes.*').

For performance reasons, it is better to use explicit paths with a class name instead of * if you are importing a single class.

There's more...

If you want your classes to be imported automatically like the Yii core classes, then you can configure global imports in your main.php configuration file:

return array(
   // …

   // global imports
   'import'=>array(
      'application.models.*',
       'application.components.*',
       'application.apis.lyrics.*',
      'application.apis.lyrics.includes.*',
      'application.apis.albums.AlbumFinder',
   ),

Note

Note that using *, with a huge amount of global imports could slow your application down as there will be too many directories to check.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.