Yii 2 Learning Your First PHP Framework

I’d like to start today’s post with a big thanks for the positive reviews I’m getting on GoodReads.com, please add yours if you can.

Also, a big thanks to everyone who has emailed me with supportive comments for the Yii 2 For Beginners book and for the positive comments on this blog.

I’ve made it my mission to help introduce people to the wonderful Yii 2 framework, and I know from first hand experience how hard it is to get up and running on something as big as a PHP framework, especially if you’ve never worked with one before.

The decision to use one framework over another is a personal choice. The major frameworks that I talk about, Yii 2, Laravel, and Symfony, are all great frameworks. You have to pick the one that suits your development style and this can certainly be a challenge when you haven’t worked with them because how are you supposed to know how well it fits?

Well, it’s like expensive clothing, you won’t know if it fits until you try it on. Obviously I’m recommending Yii 2 as the first choice among the frameworks from my point of view. Here’s why:

Top 10 reasons I would start with learning Yii 2:

1. Yii 2’s Advanced Application Template. This template comes with a working user model that includes registration, login, and forgot password functionality right out of the box. It also includes backend and frontend separation, so that you are clear on how to structure your admin area. You can get up and running quickly.

2. Gii. Yii 2 has an amazing code generation tool named Gii, which helps you stand up your models, controllers, and views quickly. The generated code almost always needs refinement, but once you know how to do that, things move along with lightning speed. It takes about 2 minutes to generate 8 files, a model, a search model, controller, and 5 view files. You’ll be amazed how far you can go in so little time.

3. Clear MVC pattern. Yii 2 has folders named models, controllers, and views, so the application structure is just what you would expect from an MVC.

4. No Routing. Most of the other frameworks require you to explicitly name the routes through the site, which can be tedious and at times confusing. Yii 2 handles this automatically. Of course you can set things like pretty URLs and any other customizations that you need, but the basic routing is handled by the framework. This is makes it very easy and intuitive to work with.

5. Widgets. Yii 2 supplies an incredible number of widgets to help develop your application. They cover everything from GridView, Pagination, Forms, DatePicker, etc., it really is impressive what you get out of the box. The widget class is easy to extend, so you can quickly build your own widgets. And once you start using these, you will get spoiled very quickly because you will want to use them for everything.

6. Mobile-First Bootstrap. So right out of the box, Yii 2 incorporates Twitter Bootstrap, which of course is device-responsive, so you can jump into mobile-first design right from the start. Wouldn’t you love to pitch that to your client?

7. Validation Made Easy. Validation in Yii 2 is handled on the model, with a very intuitive Rules method that simply holds an array of settings. The settings include the name of the attribute you wish to validate, the validator, and the options.

For example, do you need to make your email addresses unique so two users can’t have the same email address? It’s one line added to the Rules method.


['email', 'unique'],

It’s that simple.

8. Behaviors. Yii 2 incorporates a method named behaviors in both the models and controllers and this is another intuitive winner. In models, behaviors are used to manage events, like automatically inserting timestamp for creating and updating records, which is a useful behavior for a model to have. You can see how intuitive that sounds.

On Controllers, behaviors help you manage access control, things like restricting pages to logged in users only. Again, very intuitive and easy to work with. You can reference some of the tutorials on this blog for examples.

9. Native ORM. So first, what is ORM? According to wikipedia:

Object-relational mapping is a programming technique for converting data between incompatible type systems in relational databases and object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language.

It’s a perfectly scientific explanation, but I don’t find it particularly helpful. We can break it down to something more digestible.

In the simplest terms, the ORM manages how your application communicates with the database, greatly simplifying the syntax. Example:

return $users = User::find()->asArray()->all();

The above code returns all the users from the user table in an array. No having to open a connection, no SQL, no binding parameters, no specifying fetch mode, etc. It’s just one line that reads like a sentence. Look at how simple that is!

Because Yii 2’s Active Record ORM is native, it is integrated seamlessly into the framework, and this is one of the reasons why Gii is so effective at generating code. The other frameworks use Doctrine, which brings with it the excess baggage of their repository structure etc., and in my view, making it more complicated and less efficient.

10. Enterprise Capability. If you are just starting out with framework development, you are probably not ready to jump into enterprise development. But wouldn’t it be wise to learn the framework that can take you there? Learning Yii 2 ultimate builds value into your career as a programmer.

Ok, so that’s my short list of why I would start with Yii 2 as opposed to some of the other choices out there.

The key to learning a PHP Framework, if you have never done this kind of development before, is patience. Yii 2 hands you an amazing amount of features, but you have to be willing to take the time to learn them.

Another key to success in programming is this: Don’t quit. Just keep going until you get it. You will get it.

Yii 2 has a great community that is willing to help you. Also, I wrote a book that can get anyone with a moderate amount of PHP skills up and running quickly.

I’ve also augmented that with free tutorials on this blog, and I’ve also included bonus material into the book. Everyone who purchases the book gets the free bonus updates for the life of the book. I plan to keep working on it for the foreseeable future.

Working with a PHP framework is a journey, not a destination. It’s hard work but it can also be a lot of fun. I’m very happy to share this journey with you.

Thanks again for all the positive comments and reviews. As always, any comments, reviews, word-of-mouth referrals, are greatly appreciated.

Advertisements

Yii 2 Custom Widgets

I hope everyone’s new year is off to a great start. Special thanks to everyone from around the world who has purchased Yii 2 For Beginners, I really appreciate your support. I also appreciate the positive ratings and reviews I’ve been getting, for example the two I got recently on GoodReads.com.

Your positive feedback keeps me motivated and recently I added over 100 pages of new material to the book. Anyone who purchases the book gets free updates for the life of the book, just log into your leanpub.com account to get the latest.

One of the recent additions to the book had to do with creating your own widgets. For those who are unfamiliar with Yii 2’s widgets, they are very handy for presenting data in the view. Yii 2 ships with a number of time-saving widgets that cover everything from navigation, grid results, pagination etc.

An implementation of a widget could start with a single line of code in the view:

echo GridView::widget(['dataProvider' => $dataProvider,]);

But typically with GridView, you will have a lot of customization of the columns and data-display formats, so the array inside the method signature can grow quite a bit.

Here’s what you might see from a basic user model in a backend admin view:

echo GridViewWidget::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],

'id',
'username',
'email:email',
'status',
'created_at',

['class' => 'yii\grid\ActionColumn'],

],
]);

I’m not going to go into too much detail here, but you can see that the data is provided by the $dataProvider, and I don’t know how it can possibly be more intuitively named, so you have to love that.

The $dataProvider instance is being handed in from the controller, so you don’t have to supply any additional logic in the view. Next you supply it with a filter model, which is again handed in from the controller. Then you simply list the attributes you want to appear in the view.

The format of the email attribute creates a mailto link, and there are many ways to manipulate the appearance of the data.

We are also supplying classes for the look of the columns and a separate class for the ActionColumn, which contains icons and links to view, update, and delete individual records. This is just incredibly powerful out-of-the-box, especially if you are doing rapid prototyping of an admin area. We setup a much more complex version of this in the book, but you get the basic idea here.

One of the big points here is that you don’t need to put a foreach loop in the view, the widget takes care of it for you. So the widget is more of a configuration tool, not really doing much logic, and this helps to make your views incredibly clean. WordPress is chomping the code, so I can’t show you the shortcut echo tags, but you can use the shortcut because this is all really just one line, a bunch of settings handed into the array that sits in the method signature.

You will see very quickly how easy a widget is to place inside of a view, so much so that it spoils you a little. You're going to want a widget for everything.

While that’s not really practical, the good news is that you can easily create your own custom widgets. This article is more of an overview than a tutorial, so I’m not going to cover the complete setup, but I will give you an idea how it works.

Your widgets will extend Widget, with Yii 2 providing the perfect class structure for you to create these wonderful helpers. You start by overwriting your widget's two main methods, init and run.

Init just does the logic you want to perform, the result of which will be stored in the properties that you have named in the class. Then to pass the property values to the widget view, you use the run method, which renders the view with the values you have calculated in the init. The widget view is typically only a partial, which is going to sit inside of another view, making it portable and reusable.

So if you want to create a widget holding a top ten list from your content, and then use it multiple times on your site with just a single line call inside your view, you can do it. This is powerful stuff.

The cool part is how you hand in configuration from your widget call to the widget class itself. The Widget class is already structured to be able to receive an array. So you just set the array as a class property, and when the widget is called, the values of the array get handed in. Then you can use these values in the init to perform the logic you need for formatting the data.

Example:

echo MyWidget::widget(['settings' => ['pageSize' => 3]])

So imagine you wanted to build a widget where you had some results and you wanted to control the page size for pagination. In your MyWidget class, you would have a property declared as $settings = [];

In the code example above, you can see that we created the key/value pair that goes in this array, so this is assigned to the class property when the widget is called. So in your init method, you could perform logic using $this->settings[‘pageSize’] however you want. It’s that simple to move the data in. If this isn’t clear from my description, don’t worry, when you try it for yourself, you will see how it all fits together.

Although your run method need not include a view, it’s better to do it that way if you are creating output that involves html or css, which will most likely be the case. Then you just need to remember that when using the render method from within run, you need to access the properties via keyword $this, because unlike a controller, they will not be available to you otherwise.

The only other slightly tricky part to all this is setting up the application to have visibility on your custom components, which will be in its own components folder, and have its own namespace. I provide a full working example in the book, but that’s too much for here, so consult the Guide for instructions on that. Their widget section is fairly easy to follow.

Once you’ve had a chance to work with Yii 2’s widget architecture, it’s difficult to imagine coding life without it. I see it as yet another huge advantage of selecting Yii 2 as your choice for framework.

Yii 2 for Beginners Bonus Material Released

I’m happy to announce that the first chapter of bonus material for Yii 2 For Beginners has been released. The book has gone from a previous page count of 290 pages to 412 pages, so this is a very substantial addition.

Everyone who purchases Yii 2 For Beginners gets FREE updates for the life of the book. Just log into your leanpub account and download the latest version. I’m planning to continue to do updates and write bonus material for the foreseeable future. There are a number of reasons for this.

1. Striving For Excellence. I want to build a reputation for excellence and quality as a technical writer and I’m deeply committed to this project.

2. Framework Updates. I want to stay on top of Framework updates. The latest version of Yii 2 is 2.0.2, released two days before I released my bonus material. This meant I had to frantically rebuild the entire application from scratch, following the directions in the book, just to make sure everything is working. There were a few minor changes and I caught them all.

3. Maintaining the Template. The template we build in the book is a useful template for creating sites, including my own. I need to stay on top of version changes as much as anyone else, and as I’m doing that, it only makes sense to share the version improvements with my readers.

4. Sharing the Journey. Working with Yii 2 is an amazing experience that I would like to share with my fellow programmers and engineers. Working on this book is a way to express my passion for Yii 2 and grow at the same time.

I’d like to thank everyone who emailed or commented for the wonderful feedback, especially the positive reviews on GoodReads.

I really appreciated the notices on the typos as well. Most of the typos are trivial, but I still want to correct them. I won’t be satisfied until the book is 100% free of typos and I think we are probably close to that now.

I know for a fact the code is 100% working. The build I did over the past few days was from code taken directly from the book, via the gists, and it works perfectly. For anyone who doesn’t know, a gist is a code snippet hosted by Github.

Copying code from a PDF can be a real pain and I had multiple requests from readers to post the code. So, in response, I have supplied a gist for any block of code that is over 3 lines. The gists are inline in context in the book, so you just click a link and you get the relevant code. This means you don’t have to bookmark or organize anything, it’s already done for you.

New in this Update

1. Yii 2 Version Update. I already mentioned that Yii 2.0.2 was released a couple of days before I finished and this was perfect timing for me. The three notable changes concerning the template were:

A. The advanced template doesn’t ship with a role column on the user table like it did before.

B. Forgot password methods changed.

C. The typo generated by Gii when creating a controller has been fixed.

So nothing here required any dramatic changes on my part, just some instructional text had to change. This worked out well. I should point out that I ran into an unknown problem when I tried to run composer update, composer just got hung up. Another user experienced an issue as well.  My work around was to build from scratch. I had to do this anyway because I had to test everything 100% on a new build. My code is 100% compatible with both Yii 2.0.1 and Yii 2.0.2. If you do a fresh build, everything will work perfectly.  So that’s the good news there.

2. Fine Tuning Core Book. Doing an update always gives me the chance to go back over the instructions in the book to fine tune them for maximum clarity. I also catch typos, and obviously any bugs in the code. I can’t claim a 100% on typos, but I know the code is 100% working because I use it myself, and like I said before, I just rebuilt the application from scratch using the code from the book. Nothing in the core book changed in terms of how we were doing things, so nothing of substance to report.

For those that don’t know, the core book takes you through setup and install of Yii 2, then onto building a reusable template that also includes:

  • A Working user model
  • User registration and login
  • User Profile
  • Forgot password recovery
  • Frontend and backend separation with Admin UI
  • Helper classes
  • Access control
  • Free/Paid content control
  • RBAC with backend UI
  • JUI DatePicker
  • Bootstrap Mobile Responsive CSS
  • Facebook Social Widgets
  • Font-Awesome Implementation

The bonus material extends the core template with useful features, at the same time, we continue learning more about the framework.

3. Autoresponder. In the bonus material, we build an auto-responder. This is similar to the one I talk about on the blog, only this is the full set of instructions, with tested code. So again you know it’s 100% working.

4. Dropdown Navigation. We implement dropdown navigation links from my own solution. It’s quick and easy and you will love it.

5. We build an FAQ model for the template. FAQs are common to most sites and this will come in handy. This implementation has a full frontend/backend UI with extensible data structure. It is very useful code.

6. Components. We build the component application structure and show you how to create a component in the Advanced Template, including all the config details.

7. Custom Widget. Creating widgets are easy once you know how. This is a very powerful piece of the Yii 2 architecture that you will fall in love with. I will be blogging more about this in the future, it’s just amazing.

8. Closing A Potential Hole. There is no hole in the code if everything is coded correctly, but what happens when someone makes a typo? This section makes a nice adjustment to the ValueHelpers class that helps prevent accidental exposure.

9. CDN. We finish the first round of bonus material with a simple config implementation to use CDN for the core CSS and JS assets. This can dramatically increase the speed of the application.

All in all, it’s over 100 pages of new material. To reiterate, this is all 100% FREE to anyone who has previously purchased the book. Just log into your leanpub.com account to download the latest version.

I really had to work hard to get this to you in a timely manner. I put another book-writing project on hold, so I could make sure I live up to the commitments in supporting Yii 2 For Beginners. Now I need a few days off before I collapse from exhaustion.

Thanks again to all the readers from all over the world who were supportive with positive comments and are supporting my work. Your feedback motivates me to keep going. For example, on GoodReads, we are averaging 4 out 5 stars, with some nice comments even from the lower rating, which came before the additional 100+ pages of material was added to the book.

Please keep the comments, links, positive reviews, and word-of-mouth-referrals coming, they are greatly appreciated. See you soon.

Yii 2 Gii code generation

One of things about Yii 2 that is drastically different from some of the other frameworks is Gii, it’s code generation tool. I cover the use of Gii extensively in my book, Yii 2 For Beginners.

On the surface, this might just seem like a fun feature to use, a time-saver in certain circumstances. And that’s probably true of a lot of code generators, they only take you so far. But Gii is different.

Gii is so powerful that it has very meaningful impact on work flow. And this impact reaches deep into our profession. You can look at it from two perspectives, one, the individual developer doing work for clients, and two, from a team perspective, which can bring you up to full enterprise level.

So let me talk first about how it impacts the individual, and since a lot of my readers are beginners, it will help them understand the importance of Yii 2 and Gii.

1. Planning. Use of Gii impacts planning. Before you code a single line of code, you can factor in not only the efficiency of Gii, but also the workflow.

For example, to start, you look at the scope of the project and begin sketching out the table structure. The more well-thought out this data-structure is, the useful Gii becomes. If you use foreign keys to relate tables, Gii will understand this and generate relationships in the models.

This gives you the ability to imagine the project, and better yet, diagram the tables in MySql workbench, before any PHP is involved. And once you know the number of tables you are working with, you will have some idea of how long basic development will take. This is possible because you can average how long each table takes to convert to model to controller to view.

In a typical implemenation, there are 8 files generated. And they also typcially need customization, but once you have an idea of what you generally use for that, even the 1st level of customization goes quickly. When I say quickly, I mean crazy fast. It’s awesome. Awesome is not a technical word, but you have to give me a pass on that one, I really love Gii.

2. Strong MVC Pattern. The code that Gii generates is a beautiful implementation of the MVC pattern. It’s probably the easiest structure to follow of all the frameworks because you literally get folders named models, controllers, and views. And once you understand how it’s all stiched together, it just makes perfect sense.

3. Learn Good Practices. As your workflow and project planning are impacted by Gii, you begin to develop a discipline to the structure. While you are certainly not locked into anything, if you follow the breadcrumbs of good practices that Yii 2 and Gii are putting out there for you, your project becomes very tight and focused. Things are always done the same way, at least at the base level.

It’s understood of course that I’m talking about the bones of the project, not the skin. Presenting the data in the views often requires a lot of customization, but of course Yii 2 helps you bigtime there too with its widgets. But the widgets will have to be the subject of another post.

4. Grow As A Developer. As an individual developer, you build value into your skill set by following best practices. Today you are an individual developer or student. Tomorrow, you may work in a team environment. And those looking to hire programmers are looking for programmers that can follow a discipline and they’re most likely looking for programmers who have framework experience. And the good news is that this is a very accessible framework. You can learn it and benefit from it.

And that gives us the perfect transition to talk about team development. All the benefits that individual developers get from using Yii 2 and Gii are amplified in team and enterprise development. While time estimates are also important to individual developers, they can be absolutely critical in a company environment, where commitments are made to clients or to the backers of a venture.

So you can look at the list of benefits like this:

1. Workflow Standardization. The planning and flow of the project always follows the same path. Team members are assigned specific roles, which is certainly not unusual, but knowing the power of the framework and the capabilities of Gii enhances the strategic deployment of those resources.

2. Common Starting Point For Code. If the conversation starts with data-structure, it will lead to using Gii, in most cases. Obviously there are exceptions to everything. But to the extent that Gii gives us a common starting point for code, it gives the security of building a proven structure. The tight association it creates between model, controller, and view is not something you want to go out of your way to break, unless you have very good reason to do so.

3. Rapid Prototyping. Gii gives you the ability for rapid prototyping. Companies rarely have the luxury of asking “what if?” But with Gii, you can do that. You can even set aside a prototype branch with a separate DB, and playout those whatif scenarios quickly. No company would ever do that unless they could do it quickly and efficiently. But having that ability can give you a competitive advantage, so this is great.

4. Security Of Standardization. Lastly, I should state one of the most obvious benefits to the standardization that both Yii 2 and Gii offer. What if someone leaves the team? Someone else will have to take over their responsibilities, and wouldn’t it be better to know that they can do that efficiently because the structure and discipline of Yii 2 and Gii were adhered to? Of course it would. That’s a big reason why companies use frameworks in the first place.

Besides all the reasons I stated about the benefits of using Yii 2 and Gii, I thought about why it is so good at what it does and why I haven’t seen a competing framework offer something as compelling, at least not from my point of view. And I think the answer is that Yii 2 has it’s own native ORM implementation, which just makes their code generation seemless.

Having their own native ORM also gives Yii 2 the freedom to structure their MVC implementaion how they wish, so they’re able to keep it intuitive, without having to make sacrifices because of 3rd party ORM or other considerations. I believe this is a huge advantage and is one reason why Yii 2 is able to offer so much out of the box. If you haven’t tried this framework, I would strongly encourage you to do so.

I’d like to take a moment and thank all the programmers from around the world who are reading my blog, I hope you are finding it useful. And thanks again to everyone who has supported my book. Feel free to contribute with your own comments, links, and reviews, it is greatly appreciated.

Yii 2 For Beginners Update

Happy New Year Everyone!  I hope 2015 brings you joy and happiness.  I’ve been hard at work during the holidays to take care of bugs and typos in my book.  Even though Yii 2 For Beginners is only 64 days old, there were some minor changes to Gii and some other minor points that prompted me to do a fresh install and build the entire application from scratch.  Plus, as some readers pointed out, there were a bunch of typos.  No more.  The significant typos are gone and the bugs have been squashed.

Because I went through the entire application, I was able to clarify little things that will end up saving you time.  Most importantly, I confirmed that the code is accurate.  Everything is 100% working as described in the current version of the book.  I’ll do my best to stay on top of Yii 2 changes that will affect the book as they occur in the future.

I’m also happy to announce a major enhancement to the book.  I’ve incorporated Gists, which are code snippets hosted by Github, directly inline and in context in the book.  Anywhere in the book where there are more than 3 lines of code that need to be copied, you can now launch a gist in a new window and copy it from there. This makes working with the book a lot easier. And you don’t have to worry about bookmarking anything, it’s all attached to the relevant parts of the book, so it’s all organized for you.

And the even better news is that all of this is free.  All updates to the book are free for the life of the book.  All you have to do is go to your http://www.leanpub.com account and download the latest version.

I’m also pushing hard to get bonus material written for the book by the end of January 2015.  I would have waited with the current release until then, but I know how important your time is, and I wanted to get the improvements out to you as quickly as possible.

Let me conclude this post with saying how much I appreciate the positive comments, links and reviews.  It really drives me to do more.  I absolutely love the Yii 2 framework and knowing that I can help people learn it, as others have helped me, gives great purpose to my writing.  So once again, happy 2015.  I’m looking forward to sharing a great year with you.