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 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 that 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 use a class, for example, CDbCriteria, we are not including it explicitly so PHP initially cannot find it and tries to rely on the autoloading feature; the SPL autoloader, to be precise. In most cases, the 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 the 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): 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 the 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. When developing using case insensitive filesystems such as ones used by Windows, make sure you're using the same case in both the filename and code since it can be a problem when you deploy your code to a case sensitive Linux server.

How it works...

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

application is a standard alias that points to your application's 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 with Yii's 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 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

To get the example code files for this book visit http://yiicookbook.org/code.

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 €18.99/month. Cancel anytime
Modal Close icon
Modal Close icon