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 Yii core collections


Yii has a set of collection classes used mainly for internal purposes which are not described in the Definitive Guide, but are still very useful for applications:

  • Lists: CList, CTypedList

  • Maps: CMap, CAttributeCollection

  • Queue: CQueue

  • Stack: CStack

How to do it…

All collections implement SPL IteratorAggregate, Traversable, and Countable. Lists and maps also implement SPL ArrayAccess. It allows using collections like a standard PHP construct. The following is a snippet from the CList API:

  • The following is the snippet from CList API:

    // append at the end
    $list[]=$item;
    
    // $index must be between 0 and $list->Count
    $list[$index]=$item;
    
    // remove the item at $index
    unset($list[$index]);
    
    
    // if the list has an item at $index
    if(isset($list[$index]))
    
    // traverse each item in the list
    foreach($list as $index=>$item)
    
    // returns the number of items in the list
    $n=count($list);
  • CList is an integer-indexed collection. Compared to the native PHP array, it adds stricter checks, can be used in OO fashion, and allows to make a collection read-only:

    $list = new CList();
    $list->add('python');
    $list->add('php');
    $list->add('java')
    
    if($list->contains('php'))
       $list->remove('java');
    
    $anotherList = new CList(array('python', 'ruby'));
    $list->mergeWith($anotherList);
    
    $list->setReadOnly(true);
    
    print_r($list->toArray());
  • There is another list collection named CTypedList that ensures that the list contains only items of a certain type:

    $typedList = new CTypedList('Post');
    $typedList->add(new Post());
    $typedList->add(new Comment());

    As we are trying to add a comment to a posts list, the preceding code will give you the following exception:

    CTypedList<Post> can only hold objects of Post class.
  • CMap allows using every value, integer or not, as a key. Just like in CList, it can also be used in the native PHP style, has almost the same set of OO-methods, and allows making a collection read only:

    $map = new CMap();
    $map->add('php', array('facebook', 'wikipedia', 'wordpress', 'drupal'));
    $map->add('ruby', array('basecamp', 'twitter'));
    print_r($map->getKeys());
  • There is also one handy static method named CMap::mergeArray that can be used to recursively merge two associative arrays while replacing scalar values:

    $apps1 = array(
        'apps' => array(
            'task tracking',
            'bug tracking',
        ),
        'is_new' => false
    );
    
    $apps2 = array(
        'apps' => array(
            'blog',
            'task tracking',
        ),
        'todo' => array(
            'buy milk',
        ),
        'is_new' => true
    );
    
    $apps = CMap::mergeArray($apps1, $apps2);
    CVarDumper::dump($apps, 10, true); 

    The result of the preceding code is as follows:

    array
    (
        'apps' => array
        (
            '0' => 'task tracking'
            '1' => 'bug tracking'
            '2' => 'blog'
            '3' => 'task tracking'
        )
        'is_new' => true
        'todo' => array
        (
            '0' => 'buy milk'
        )
    )
  • CAttributeCollection includes all CMap functionality and can work with data just like properties:

    $col = new CAttributeCollection();
    
    // $col->add('name','Alexander');
    $col->name='Alexander';
    
    // echo $col->itemAt('name');
    echo $col->name; 
  • CQueue and CStack implement a queue and a stack respectively. A stack works as LIFO: last in, first out, and the queue is FIFO: first in, first out. Same as list and map collections these can be used in native PHP style and have OO style methods:

    $queue = new CQueue();
    
    // add some tasks
    $queue->enqueue(new Task('buy milk'));
    $queue->enqueue(new Task('feed a cat'));
    $queue->enqueue(new Task('write yii cookbook'));
    
    // complete a task (remove from queue and return it)
    echo 'Done with '.$queue->dequeue();
    echo count($queue).' items left.';
    // return next item without removing it
    echo 'Next one is '.$queue->peek();
    
    foreach($queue as $task)
       print_r($task);
    
    $garage = new CStack();
    
    // getting some cars into the garage
    $garage->push(new Car('Ferrari'));
    $garage->push(new Car('Porsche'));
    $garage->push(new Car('Kamaz'));
    
    // Ferrari and Porsche can't get out
    // since there is…
    echo $garage->peek(); // Kamaz!
    
    // we need to get Kamaz out first
    $garage->pop();
    
    $porsche = $garage->pop();
    $porsche->drive();