Tag Archives: Yii 2 for beginners

Yii 2.0.5 Security Patch Released

Yii2 released a quick patch for the ViewAction class. You can read the release here.

I had problems when I tried to run composer update and apparently they are aware of an issue on the composer side. So if you are following along with the book and already have installed the framework, I don’t recommend upgrading until the problem is solved.

If you are doing a fresh install, then you should be fine with Yii 2.0.5. I will follow up when the problem is solved.

I will also try to carve out time to build my app from scratch with Yii 2.0.5, so that I can have a current build handy for any issues that might arise. I anticipate this will take a couple of weeks as I’m in the process of completing another book, which I will be talking about on this blog.

Also, thanks so much for the great reviews I’ve received on GoodReads.com. Right now we are 4.68 out of 5 stars average with 25 ratings and 7 reviews. I really appreciate all the support I got with this book, so thanks again.

Advertisements

Yii 2 Para Principiantes Published Today, it’s Yii 2 For Beginners translated into Spanish

I’m happy to announce that Yii 2 Para Principiantes has been published today. This is Yii 2 For Beginners translated into Spanish language by Victor Hugo Garcia.

Victor put a lot of great work into this translation, including translating class names and DB tables into Spanish names when appropriate. The translation covers the core book, up through chapter 11. After that, the bonus chapters are provided in English and will be updated into Spanish as they become available.

Anyone who purchases the book, whether it is the Spanish Version or the English version gets free updates for the life of the book. All you have to do is login and pull down the latest version.

Like its English counterpart, Yii 2 Para Principiantes will take you step by step through setup and installation, and then on to coding in one of the most exciting PHP framework available today. The book focuses on creating a reusable template that can serve as the basis for your projects, including the following features:

      Setup and install
      A Working user model
      User registration and login
      User Profile
      Forgot password recovery
      Frontend and backend separation
      Helper classes
      Access control
      Free/Paid content control
      RBAC with backend UI
      JUI DatePicker
      Facebook Social Widgets
      Font-Awesome Implementation
      Image Upload and Management
      Multiple Social Auth Providers
      Custom Data-driven Carousel Widget
    Facebook Login & Registration with one click

I’d like to give a personal thanks to Victor, who not only gave me a great review on the book at GoodReads.com, but then later also volunteered to write the translation. He put a lot of work into it, so that is greatly appreciated.

Thanks again to all the programmers from around the world who have supported the book, it makes this work possible. I hope you find the book helpful.

Yii 2 For Beginners New Bonus Material Released Growl and Rating System

I’m happy to announce today the release of bonus chapter 17, the latest update of Yii 2 For Beginners, with 60 pages of new bonus material as of 7:00 pm pacific standard time on April 6, 2015. Anyone who has purchased on or before that date, and that includes today, can login to leanpub.com and pull down the latest version of the book.

As always, updates and bonus material for the book are free for the life of the book. I highly recommend that you update to the latest version to get the most out of your purchase and take advantages of the new features built into the template.

In this bonus chapter, we utilize Kartik’s Yii 2 widgets extension, which includes numerous widgets that we will use, in this chapter, and in future chapters. Specifically, in this chapter, we will be working with the StarRatings widget and the Growl widget.

We create a functioning rating system for our Faqs, so users can rate them. You can use this as a prototype for any model that you want to have ratings for, so this is very handy.

We also implement the Growl widget, which takes a plain flash message and animates it, so you can add some life to the frontend.

We also do one cleanup task, which is to add a checkbox to the signup page, so we can have users agree to the terms of service. It’s a little detail, but since almost every application will require it, we provide a working solution.

And finally in this chapter, we return to the data-driven carousel to make it more adaptable to mobile browsers. Now, when the browser is scaled down, the carousel will switch to a mobile image that is also 100% controlled by our backend admin UI.

I felt it was really important to get this detail right. And after seeing some great comments and reviews on my book, I decided we couldn’t settle for second best, so I made sure we got what we needed. I think you will love the results.

Everyone appreciates the efforts of those who wrote in with typo notices, it makes for a better reading experience for everyone, so thanks to everyone who contributes.

I will continue to do my best to develop the template and bring you more bonus material. Any efforts on your part to help spread the word on the book will be greatly appreciated. Thanks again for purchasing the book and for your support.

Yii 2 For Beginners Update Image and File Management

I’m pleased to announce today the latest update of Yii 2 For Beginners with over 100 pages of new bonus material as of 3:00 pm pacific standard time on March 26, 2015. Anyone who has purchased on or before that date, and that includes today, can login to leanpub.com and pull down the latest version of the book.

As always, updates and bonus material for the book are free for the life of the book. Just login into your leanpub.com account and pull down the latest version. I highly recommend that you update to the latest version to get the most out of your purchase and take advantages of the new features built into the template.

I worked really hard to get this bonus material out to you, it covers a lot of new techniques, including use of Yii 2’s scenarios. The page count of the book is now over 600 pages. For those unfamiliar with the book, we take you step by step through setup and installation and then onto coding a reusable template.

The book features:

  • Setup and install
  • A Working user model
  • User registration and login
  • User Profile
  • Forgot password recovery
  • Frontend and backend/Admin separation
  • Helper classes
  • Access control
  • Free/Paid content control
  • RBAC with backend UI
  • JUI DatePicker
  • Facebook Social Widgets
  • Font-Awesome Implementation via CDN
  • Autoresponder Email for signup
  • Facebook Login & Registration with one click
  • Image Upload and Management
  • Multiple Social Auth Providers
  • Custom Data-driven Carousel Widget

More will be coming…

In this bonus material from this release, we cover basic image management, which includes uploading, updating and deleting both images and thumbnails. We also build a dynamically-driven carousel widget that is controlled by our admin UI.

You can set things like font size of the caption, show captions or not, show controls or not, etc., all from the backend UI.

This means you can hand total control of a key marketing area on the template over to the client and they will love that. Marketing is very important to clients and site admins and they will appreciate this level of detail.

I also went back to chapter 14 and added in the formatProviderResponse method both Google and Linkedin, which I had previously omitted. I’ve also included step by step instructions for setting up Google and Linked Apps, including screenshots to help you along.

While I was busy writing this update, some of our readers left positive reviews and comments on GoodReads.com, this blog, and the feedback section of the book’s landing page on Leanpub.com. This really inspired me to go all the way with the data-driven carousel and see how cool we could make it. I hope you like the results. I also hope you will contribute some positive comments and reviews of your own.

A number of readers also wrote in with typo notices and I jump on those immediately, with the turnaround within a few hours to 1 day. Everyone appreciates the efforts of all involved, it makes for a better reading experience for everyone.

Working on the Yii 2 framework is an amazing journey and I really enjoy sharing it with you. Thanks again for supporting our efforts.

Yii 2.0.3 Released

Yii 2.0.3 was released today, and while that’s great news, it means I have to make sure everything in my book, Yii 2 For Beginners, is 100% working with the update.

So, today, I ran the composer update and everything went smoothly. In about 2 minutes, I was fully up-to-date and you have to love this framework for that.

Just for those who are unfamiliar with composer, the framework files live in a vendor folder, and when you run composer update, it reads your composer.json file and brings your vendor files up-to-date with the latest versions and dependencies.

So composer knew that once 2.0.3 was released, 2.0.2 was out of date, and it stripped everything out and replaced it with the newer version. What a fantastic way to maintain a framework.

The Yii 2 advanced template is somewhat of a unique case however, because the template code lives in the backend, common, and frontend folders, and that can change with a version release. Yikes!

This means I have to check every aspect of the advanced template to see if there are any changes that impact the re-usable template we build in the book as well as the out-of-the-box code, since I take us through the complete setup and explain things like the site controller and the related form models.

I have to review all that line by line. I’m happy to report only one minor change in the login method, which I quickly updated in the book, so as of now, we are 100% code working and 100% compatible with Yii 2.0.3.

For those following along in the book, no change is necessary due to today’s version release. I do recommend that you stay current on the latest release and do a composer update.

I’m happy to say that I got the full review of the release and the update of the book done on the day of the 2.0.3 release. I know from your comments, emails and reviews that this hard work is helpful to a lot of people.

The readers of the book have been helpful too, letting me know about grammatical errors and other typos. I typically respond within 24 hours to email requests. There hasn’t been any code breaking in quite a while and we’re closing in on 100% of the grammatical errors. I really appreciate the help and it makes a better reading experience for everyone else and this is helping drive the positive reviews.

Since no other action was required on my part due to today’s release, this gave me a chance to tighten anything up that was previously less clear and to cover anything unusual.

For example, a reader wrote in to tell me that he couldn’t get the date to work on the profile model unless he added the php prefix in the validation rule:

[['birthdate'], 'date', 'format'=>'php:Y-m-d'],

I couldn’t reproduce his issue, but I thought I would mention this in case you run into a similar problem and I updated the book to reflect that.

Anyone who purchases the book gets free updates for the life of the book, all you have to do is login to your leanpub.com account and download the latest copy.

For minor issues, like the above, I generally don’t make email announcements. However, I’m also working on bonus material that I’m adding on a quarterly basis (approximately) and I have more new material coming soon, so there will definitely be an announcement with that release.

The core material in the book is 100% complete, and you can get up and running quickly with it. But the template we build in the book is also one I use personally, so I’m always working on it, and it only makes sense to share it with you. Those updates are free for the life of the book.

The other thing notable to me about today’s Yii 2.0.3 release is that this is the third minor release since the 2.0 release 4 months ago. This means you can have confidence that the Yii 2 framework is being very actively developed.

In their own words, Version 2.0.3 is a patch release of Yii 2.0 which contains about 50 minor new features and bug fixes. These include some performance optimizations for RBAC, Page caching for RESTful repsonses, and more. You can read about it here.

Even though a version release for Yii 2 is a hectic time for me, I really do enjoy it. I love the architecture of the framework, and reviewing it for a version release reminds me how easy it really is to use and how it just keeps getting better.

Let me end with a special thanks to all the programmers from around the world who participate in the this blog by reading the aricles, taking the polls, leaving comments and writing reviews. It is very much appreciated and keeps me working hard to continuously improve. Thanks again.

Yii 2 Create Method on Controller

Greetings to everyone from around the world who follows this blog. Programming knowledge does not recognize borders, which really points to how superficial borders are. I know I’ve said that before, but everytime I get a supportive email from someone on the other side of the planet, it really hits home.

I also appreciate all the positive comments, reviews, and word-of-mouth referrals on my book, Yii 2 For Beginners. Readers of the book have been very helpful in elevating the quality of the book by pointing out typos and bugs. I’m happy to say as of the last update, the code in the book is 100% working. Updates are free for the life of the book and I plan on adding material to the book several times a year.

So for those who are unfamiliar with Yii 2 or have never worked with a PHP framework before, I want to demonstrate just how powerful a single method on the Yii 2 Framework can be. This insight came to me as I was working on an idea for a 2nd book, a book on beginning PHP, for people who have never programmed before.

Anyway, I wanted to simulate a framework to teach PHP fundamentals. I didn’t build an actual framework for the following reasons:

1. That’s too intense for beginning PHP.

2. It would take me a 100 years to write the book.

3. It would be a 100 years of wasted time.

The reason why I say it would be wasted time is because of how great the Yii 2 framework is. It makes the idea of building a framework from scratch a bit silly, unless you have very good reason to do so. Why reinvent the wheel, especially when we have such an amazing wheel to work with in the first place?

Anyway, this was made abundantly clear to me as I was staring at the code I made for my simulated controller code. I used a switch statement to simulate individual actions, and this is what the create action looks like. I’ll explain each section, but to start, here it is in one ugly, proceedural block:


case('/mysong/src/controllers/songcontroller.php/create' == $uri):
                      
            if (isset($_POST)){
                
                $post = Security::sanitizeInput($_POST['form_token']);
                $session = Security::sanitizeInput($_SESSION['form_token']);
            }
            
            if (isset($_POST) && Security::matchTokens($post, $session)){
                       
            $song_name = Security::sanitizeInput($_POST['song_name']);
            $visibility = Security::sanitizeInput($_POST['visibility']);
            $video_source = Security::sanitizeInput($_POST['video_source']);
            $video_is_featured = Security::sanitizeInput(isset($_POST['video_is_featured']));
            $video_is_active_item = Security::sanitizeInput(isset($_POST['video_is_active_item']));

            if ($video_is_active_item == true){
                
                $video_is_active_item = 1;
                
            } else {
                
                $video_is_active_item = 0;
            }
            
            if ($video_is_featured == true){
                
                $video_is_featured = 1;
                
            } else {
                
                $video_is_featured = 0;
                
            }
            
            if (!Validators::validateDropDownOption($visibility)){
                
                $visibility = 'Private';
                
            }                      
          
       $cmd = new Query;
       
       $sql = 'INSERT INTO song (song_name, visibility, video_source, 
               video_is_featured, video_is_active_item) VALUES (:song_name, 
               :visibility, :video_source, :video_is_featured, 
               :video_is_active_item);';
       
       $cmd->query($sql); 
       
       $cmd->bind(':song_name', $song_name);
       $cmd->bind(':visibility', $visibility); 
       $cmd->bind(':video_source', $video_source);
       $cmd->bind(':video_is_featured', $video_is_featured);
       $cmd->bind(':video_is_active_item', $video_is_active_item); 

       $cmd->execute();
       
       $cmd->closeDb();
       
            $url = Url::toSong($song_name);
            return header('Location: ' . $url);
           
            break;
            
        } else {
        
             $url = Url::toSongCreate();
             return header('Location: ' . $url);   
             break;
        }

Anyway, we can step through this quickly. If we have post data, make sure the tokens match to prevent CSRF:


 if (isset($_POST)){
                
     $post = Security::sanitizeInput($_POST['form_token']);
     $session = Security::sanitizeInput($_SESSION['form_token']);
 }

 if (isset($_POST) && Security::matchTokens($post, $session)){

If we pass that test, then we set the variables from the form data:


 $song_name = Security::sanitizeInput($_POST['song_name']);
 $visibility = Security::sanitizeInput($_POST['visibility']);
 $video_source = Security::sanitizeInput($_POST['video_source']);
 $video_is_featured = Security::sanitizeInput(isset($_POST['video_is_featured']));
 $video_is_active_item = Security::sanitizeInput(isset($_POST['video_is_active_item']));

We’re using my homegrown Security class to scrub the input. Then we do a little formatting for the check boxes:


if ($video_is_active_item == true){
                
    $video_is_active_item = 1;
                
} else {
                
    $video_is_active_item = 0;
}
            
if ($video_is_featured == true){
                
    $video_is_featured = 1;
                
} else {
                
    $video_is_featured = 0;
                
}
            
if (!Validators::validateDropDownOption($visibility)){
                
    $visibility = 'Private';
                
}
           

I probably would have used ternary syntax if not for the word wrap issues in creating a book.

Anyway, then I use my custom-built Query class to insert the new record:


 $cmd = new Query;
       
       $sql = 'INSERT INTO song (song_name, visibility, video_source, 
               video_is_featured, video_is_active_item) VALUES (:song_name, 
               :visibility, :video_source, :video_is_featured, 
               :video_is_active_item);';
       
       $cmd->query($sql); 
       
       $cmd->bind(':song_name', $song_name);
       $cmd->bind(':visibility', $visibility); 
       $cmd->bind(':video_source', $video_source);
       $cmd->bind(':video_is_featured', $video_is_featured);
       $cmd->bind(':video_is_active_item', $video_is_active_item); 

       $cmd->execute();
       
       $cmd->closeDb();

My bind method autmatically detects string, int, etc. I had a lot of fun creating that. Then we save via execute and close the DB connection. Then we go to the newly created record or show the form if no post data was sent:


$url = Url::toSong($song_name);
return header('Location: ' . $url);
           
break;
            
} else {
        
$url = Url::toSongCreate();
return header('Location: ' . $url);   
break;
}

This is very simple and clear code, easy for a beginner to digest, but it sure did get procedural in a hurry. So I thought about extracting out the methods to further simulate what a framework like Yii 2 would do, but then I thought, hey, why don’t I just show the reader what the framework actually does instead? How would Yii 2 handle this method?

In Yii 2, we would get a single method on the controller. So I grabbed a controller method for the FAQ model we make in the Yii 2 book:


public function actionCreate()
{
    $model = new Faq();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

9 lines, not counting the white space. Now that’s power. It’s starts by creating a new Faq model, which gives us access to all the model attributes and methods. Then comes:


if ($model->load(Yii::$app->request->post()) && $model->save()) {

So what this is doing is loading the $_POST array, which gets all the fields from the form, validating it, and saving it. All that in one line of code. Wow!

If it successfully saves, it returns the view page of the newly created record:


return $this->redirect(['view', 'id' => $model->id]);

In the above, view is the name of the page we want. Yii 2 knows which model the view belongs to and $model->id is the specific instance. No other routing necessary.

If we can’t successfully save, we get the form:


} else {
     return $this->render('create', [
        'model' => $model,
    ]);
}

And that is essentially one line as well. You could style it like so:


return $this->render('create', ['model' => $model,]);

And that’s pretty much it. 9 lines and all the security, validation and formatting is already handled. It’s so simple!

Hopefully I’ve demonstrated at least one reason why I’m such a Yii 2 enthusiast. I will continue to do my best to make the framework as easy to understand for beginners as possible.

Thanks again to everyone who wrote in with encouragement and corrections, especially to those who took the time to do a review on GoodReads.com. As always, any comments, reviews, word-of-mouth referrals, are greatly appreciated.