Tag Archives: yii 2 framework

Yii 2 RBAC Tutorial

Once again a warm welcome goes out to all the programmers and developers around the world who are discovering this blog. I get amazed every day when I see the stats and the diversity in the countries represented. It gives me the hope of a common language for the world and a framework like Yii 2 is a great place to express that.

Also, thanks to everyone who has taken part in the polls on this site. Over 1000 developers have voted on many topics relevant to today’s php community. Your comments are also appreciated, so please feel free to vote and comment.

And also, much gratitude for everyone who has purchased a copy of Yii 2 For Beginners, with your support I can continue my work, and I really appreciate it.

Ok, so the topic here is RBAC. This stands for Role Based Access Control and this can be difficult to implement in any framework. The Yii 2 advanced template comes with a working user model out of the box and this makes it fairly easy to get up and running. The thing is every site needs access control, especially if you are going to have a front end and back end to the site, and if you are going to have users with special privileges, such as admin users, who will have access to admin functions in the backend of the application.

The Yii 2 advanced template conveniently divides itself into frontend and backend out-of-the-box, so there again, it’s helping you. It stops short, however, of handing you a working RBAC model with the template. The reason for this is that many applications will have many different requirements and they need to leave the framework as open-ended as possible.

Yii 2 does have an authManager component with a complete RBAC implementation that is fully scalable and robust. You can read about RBAC in the docs. And if you want to use that, it’s perfectly fine. Personally, I found it to be a little rigid for my needs.

This is not saying anything bad about what they have, it’s just it’s impossible to anticipate every scenario, and its easier to build something to suit your own needs than follow someone else’s pattern. Plus there is a learning curve as there is with everything.

This is one of those instances where I really feel it’s better to write your own code, you will be closer to it, and it will be easier in the long run for you to work with it. Some may disagree with that statement, but like a lot of things in programming, it comes down to personal preference, so feel free to decide for yourself.

In my book, I layout an RBAC pattern that is easy for beginners to grasp and is something you can build on. But since it’s meant to be a little more robust for long-term use, it doesn’t lend itself to a quick tutorial.

At the same time, I noticed in the forum that there were a lot of people asking about how to implement RBAC. So I asked myself, is it quick and easy for someone to get up and running with RBAC if they just want user/admin roles? No. Wait… Yes it is!

I came up with a six step RBAC tutorial, which I’m linking to because I made a wiki tutorial out of it on the Yii Framework site.

You will need to have a fresh install of the Yii 2 advanced template. They have a complete set of setup instructions there. I cover it extensively in my book, with a bunch of jpgs to help you see what it is supposed to look like.

Anyway, for the tutorial, it’s a more basic version of what we cover in the book. I was able to bring it down to just six steps, it doesn’t require any outside plugin or extension, and you can do it in less than 20 minutes. I’m really happy about that.

It also uses Yii 2’s matchCallback method on behaviors, which I felt was good way to do it, since it leaves the main controller actions less cluttered. It’s really easy to implement.

Now RBAC is not the first subject you should jump into if you are just starting with Yii 2, and depending on your skill level, it can be difficult. The six step tutorial is about as simple as it gets, but you need to get the advanced template setup and working first, so make sure you have done that step before moving into RBAC.

On the other hand, I don’t know of any other php framework that can move you so far along, so quickly with RBAC. Yii 2 does 99.9% of the work, you have to love that.

Got my first book review from Vegibit:

“Another great resource is a great book by Bill Keck who maintains a blog about Yii. You can get the book at leanpub right here. It’s a great resource because it takes the perspective of someone who is new to the framework and is diving in with a self learning crash course in getting things working with Yii. This real world approach is valuable in learning the key concepts when the rubber hits the road so to speak.”

Feel free to add your comments below. We would love to hear from you. Thanks again for your support.

Yii 2 Dropdown Navigation

Yii 2 Dropdown Navigation and Menu tutorial

I would like to extend a warm welcome to all our friends from around the world who are just discovering this blog. Doing this blog, and seeing all the traffic from so many countries, it really does show me how much we all have in common, no matter where we are from. International bounderies are just an artificial construct, and not necessarily a good one. But as programmers and developers, we get to transcend all that and play in a very fun space.

Speaking of fun, over 1000 developers have taken part in the polls on this site, and I would encourage you to participate, either by voting or commenting or doing both, let your voice be heard.

You may have heard me say this before and most likely, you will hear me say it again:

Thanks to everyone who has bought Yii 2 For Beginners, I appreciate your support.

Now anyone who knows me knows that I try to avoid frontend development as much as possible. It’s like God invented frontend development just to irritate backend developers, who otherwise just enjoy coding a little too much. But with Yii 2’s native integration of Bootstrap 3, a mobile responsive css out of the box, there’s no reason to feel that way.

Yii 2 has a number widgets that make integrating with Bootstrap easy. The tricky part is finding the documentation on them. I was following the forum and saw a lot of questions on Dropdown Navigation or a dropdown menu, as in, how do we do it? That’s a really basic question, everyone will need this at one point or another.

Now trying to be helpful, I searched for the answer and came up with nothing. I even dug into the source code of the widgets to see if I could figure it out. Somewhere along the way, I figured it out. Of course I have no way to know if this is the “official way” to do it, but I’ve tested it and it works. So here is the implementation:

Yii 2 Dropdown Navigation:


echo Nav::widget([
                'options' => ['class' => 'navbar-nav navbar-right'],
                'items' => [
        
                            ['label' => 'Top Label', 'items' => [
                            ['label' => 'Action', 'url' => '#'],
                            ['label' => 'Another action', 'url' => '#'],
                            ['label' => 'Something else here', 'url' => '#'],
                        ]],
        
                    ],
    
            ]);

Turns out it’s just a nested array inside the items array. So simple! I know they are working on the documentation and that Yii 2 has just been released, so we all just have to have patience as they put all the docs together. They are doing a good job of it, the doucmentation they have is clear, we just need more of it.

Another request I see often in the forum is for a working RBAC solution. I’ve developed a nice solution in Yii 2 For Beginners, it’s easy to implement, with a full backend UI, but it’s one of the more extended lessons in the book and it’s too big for a blog post.

Getting back to the Yii 2 DropDown Navigation widget, please remember you have to echo the widget inside the view. That means you have to place it within Php tags. Also, if you want to the dropdown navigation inside the existing Navbar widget that comes with the default Yii 2 installation, you need to place it somewhere within the widget begin and widget end tags:


NavBar::begin([
                'brandLabel' => 'Yii 2 Build <i class="fa fa-plug"></i>',
                'brandUrl' => Yii::$app->homeUrl,
                'options' => [
                    'class' => 'navbar-inverse navbar-fixed-top',
                ],
            ]);

//your nav widget somewhere inbetween.

NavBar::end();


Another tip is you can see I included a call to font-awesome’s fa fa-plug in the brandLabel parameter of the NavBar widget. Font-awesome is a great library and most likely, you will want to include in your project. It’s also a topic, we cover in the book.

Just keep in mind that if you come up against a situation like not knowing how to do a dropdown menu in Yii 2, the answer is out there and someone will help you. The Yii 2 community is very active and willing to help. It’s a great framework and I’m committed to helping you make the most of it.

Yii 2 Framework Development

Welcome to anyone from around the world who is just discovering this blog. It’s amazing how programming transcends international boundaries, which were always artificial anyway. Over 1000 developers have taken part in the polls on this site and I would encourage you to participate, either by voting or commenting or doing both, let your voice be heard.

Also, thanks to everyone who has bought Yii 2 For Beginners, I appreciate your support.

I recently discovered this Youtube video on the development of the Yii 2 framework.

I would strongly encourage you to watch the video, it’s about 3 minutes long. It shows a time-compressed evolution of the framework, starting with the first development by Qiang Xue, quickly followed by Alexander Makarov (Samdark). Then as the video progresses, you see some of the other Yii 2 stars such as Carsten Brandt (Cebe) and eventually Kartik V. popping in to make some contributions. Over 300 developers contributed to the making of Yii 2.

This video is just fascinating on so many levels. For one, you get to see how Yii 2 starts, with Qiang Xue laying out the base classes. Who knew that validators were such a big group of classes? If you ever wondered what the founder of Yii actually did, here it is in graphic detail, played out against some pulse-pounding music.

You also get to see how Yii 2 grows as a codebase, and how that intensifies as more developers come into to contribute. Entire branches of the framework seem to suddenly emerge as the energy pours in from the community. Each update is represented by a small spotlight effect or maybe it’s a small lightening bolt. Anyway, it’s pretty cool.

The representation of the project is made possible through Google’s Gource software, which extracts the updates from Github and compiles them into a video.

I’ve already done a lot of comparisons to Laravel on this site, but there is even a version for Laravel. One myth that dispelled for me was that I thought that Laravel was only one person, but you can see from the video that there were many people involved. Also, I think the video gives the impression that Laravel is lighter than Yii 2, but I think this is because Laravel depends on Symfony 2 and Doctrine, and obviously, that is not included in the Gource.

In some ways, the two videos draw a nice contrast between the two frameworks. The gource for Yii 2 is the entire framework, (up to the date it was made), the gource for Laravel can’t be because it’s layered on other dependencies. So no matter how gracefully that is handled, and Taylor Otwell did a great job, no doubt about that, it still is not quite the same as a single integrated entity like Yii 2, where the parts fit together seamlessly.

At this point, I can’t really claim objectivity, since I wrote a book on Yii 2, but I do think these differences matter. For example, Yii 2 really sticks to the MVC pattern in an intuitive way. You get folders named, Models, Controllers, and Views. You get files with names like Site Controller.php in the controllers folder. Yii 2 does the routing for you, whereas in Laravel, and Symfony 2 and Zend 2 for that matter, you have to set all the routes manually, and that is every route through the site explicitly declared, which is a big pain.

I think you can see from the video that a lot of effort went into the creation of Yii 2. So let’s conclude with another thanks to all those who contributed to the making of such a great framework. Feel free to let us know what you think, we would love to hear your comments, thanks for participating.

What do $foo and $bar actually mean in PHP?

Let’s start with a warm welcome to anyone from around the world who is just discovering this blog. Over 1000 developers have taken part in the polls on this site and I would encourage you to participate, let your voice be heard.

Also, thanks to everyone who has bought Yii 2 For Beginners, I appreciate your support. Starting this week, I will be adding tutorials on Yii 2 that build off of examples in the book, so I hope this can be a great resource for you.

Ok, so what is up with $foo and $bar? The use of $foo, and it’s companion $bar, in examples and lessons has always bothered me. One reason for that is that I know the origin of the composite word, Foobar, which is derived from fubar. Fubar is an epression that started in the US military. It stands for “fucked up beyond all recognition.”

So once upon a time, in the early days of programming, someone apparently thought it was clever to use a phonetic variation of fubar, split in half to use in programming examples. In other words, it was a joke. It was a joke, however, that caught on, and so now we seem to be stuck with it.

So what’s wrong with that? Ok, here’s the problem. Some people, like myself, know the origin of the word. The word itself has meaning. That meaning gets injected into the example on a subliminal level, which distracts from understanding the objective of the lesson.

Also, since $foo and $bar combine to represent a single word, the first thing I always try to see is if they are meant to be related that way when they are used in an example and more often than not, they are not meant to be related, though in some cases, one is used as a child of the other. You can see how confusing this can get.

It’s not that I don’t have the brain power to overcome the inference of fubar, but on the other hand, I would rather not waste bytes or neurons, precious as they are, on something like that. I have a much better use for them elsewhere.

Now you could say I’m in the minority, and that most people, especially those around the world who don’t speak english as a first language, are not going to have that distraction and you would be right about that. However, $foo and $bar still make for bad examples. Here’s why:

Even without the inference, using $foo and $bar is like using $could_be_anything_1 and $could_be_anything_2 or as the way my brain sees it, $lazy_example_1 and $lazy_example_2.

Wouldn’t be better for example, if you were going to explain arrays to people, to do it in a way that also points them in the right direction for future use and future lessons. For example, here we have a snippet from PHP.net on the new array syntax:

// as of PHP 5.4

$array = [
"foo" => "bar",
"bar" => "foo",
];

And look, they used my favorite word for the example, I didn’t have to go far to find someone using it. So just to reiterate why this is so bad, the first key is foo and has a value of bar, the second key is bar and has a value of foo. Does this mean they are interchangeable in the code and that they are equal to each other? Of course not. Arrays don’t work that way. But imagine you were just learning. You could see how that would potentially be confusing.

Robert Martin, Author of Clean Code, uses an interesting phrase, “lies and disinformation.” He is referring to comments in code that grow outdated in time because they are not maintained as the code changes. A bad choice of language in tutorials and examples is just as harmful. It slows down the learning process and makes it less fun.

Imagine the poor guy just learning PHP and programming having to spend an extra ten minutes of his time to realize that foo and bar are not equal to each other. If that happened to me, I would be angry and want my time back. Nothing is as precious as time and anything that degrades it in a learning enviroment is as bad as “lies and disinformation.”

Imagine an array example instead:

// as of PHP 5.4 example array named basket, where “string” is key and integer is value:

$basket = [
"apple" => 1,
"cookie" => 4,
];

Now obviously, there is a little more color to the example. Also I added more to the comment for clarity, even though those aspects might be explained elsewhere. It doesn’t hurt to have it there, because when people do a Google search, they may come directly to this snippet, you never know.

Why choose the word $basket? Well, what would a future or current programmer possibly work on that would require an array? That list is probably endless, but one good example would be a shopping cart. And right away, as a human, I’m a lot more interested in the example. Arrays might be fun if I can play with apples and cookies. I might even start to get creative about what I can do with the basket.

So obviously this is as basic as it gets, but it does have implications. We have seen a movement in modern PHP towards more clear snytax, and what I mean by that is code that makes its intentions more clear.

The modern PHP frameworks like Laravel and Yii 2 have done a good job making the code more intuitive. In fact I think Taylor Otwell, Laravel inventor and developer, has been very influential in this regard. I initially found his framework very attractive, but then Yii 2 came out and as you can tell from the history of this blog, and the book I wrote about it, I fell in love with it.

An example of excellent and intuitive syntax in Yii 2 is the behaviors method that you can use on either a model or a controller. We’re about to take a quantum leap in complexity from the array example, but as long as we give a good example, we will understand it.

A typical implementation of behaviors in a model would look like this:

public function behaviors()
{
  return [
     'timestamp' => [
          'class' => 'yii\behaviors\TimestampBehavior',
          'attributes' => [
              ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
              ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
          'value' => new Expression('NOW()'),
            ],
        ];
     }

Screenshot of the code with no scroll:

yii 2 behaviors

If you are following along from the book, this example appears in the User model and Profile model. We use a different type of behavior for controllers, but you can get a clear idea of how cool and how flexible this concept is.

TimestampBehavior is one of Yii 2’s out-of-the-box behaviors, so everything is in place that you need to attach it to any model. All it’s doing here is automatically setting the value of two attributes, ‘created_at’ and ‘updated_at’ with a ‘value’ of ‘NOW()’ before insert or update.

This means before any record is created or updated, the timestamp value is set, and, assuming that you have the corresponding columns on your DB table in DATETIME format, you will get the desired result and the fields in your table will be updated with the current DATETIME.

Can you see how intuitive the concept is and how clear the code is? Anyway, let’s just step through this to make sure we understand it.

By configuring the behavior, we influence how the model will work. We give the behavior a name, in this case ‘timestamp.’ We tell it what class to use, in this case ‘yii\behaviors\TimestampBehavior.’

Next we tell it which attributes we want to affect, and we use ActiveRecord::EVENT_BEFORE_INSERT to tell it when and how to use it. In other words, it will set the value of the attribute before inserting or updating, which is made fairly clear from the name of the event.

And then finally, what ‘value’ we want to give it. We’re using an instance of the expression class, which let’s us define what type of value we want, which allows us to pop in the MYSQL syntax ‘NOW()’, so ActiveRecord can hand it into the insert statement.

You know the syntax is well-written when it is easier to understand than the verbal explanation. At least it seems that way to me. I’ve been staring at it for a while now. It just seems clearer and clearer to me, which is always a good sign.

Now imagine the above example as:

 public function behaviors()
    {
        return [
            'foo' => [
                'class' => 'foobar',
                'attributes' => [
                    qux => ['baz1', 'baz2'],
                    qux => ['baz2'],
                ],
                'value' => new Expression('quux'),
            ],
        ];
     }

Screenshot of the code with no scroll:

bad behaviors

That’s not realistic, no one would do that to you, at least I hope they wouldn’t. Anyway, I think you get the point. A real example makes you want to play with the system. A $foo/$bar example is just fubar. Feel free to take the poll and let us know what you think.

Yii 2 For Beginners

I’ve been studying the PHP framework scene for the last 3 years in depth. I’ve done comparisons on all the major frameworks, including Laravel, Symfony, and Yii, and in the end I chose Yii 2 as my framework of choice. You can see a little of the history of this, my blog, Yii 2 vs. Laravel, talks about discovering Yii 2 when it was only in Alpha. After trying all of the other frameworks, watching countless videos and reading many books, I settled on the one PHP framework that had no book whatsoever to help beginning programmers.

I always felt, if only there were a book for beginners, I could learn this quickly, I just needed someone to point the way. Instead, I learned piecemeal by gleaning tips from the forum, the guide, and from the fact that the framework was very intuitive. Even though I made progress, I still found myself wishing for the book. Learning this would be so much easier, if I just had a book!

How ironic is it that 6 months later, I end up writing the book I yearned for? Well, I kept very detailed notes on my development and I noticed over time that I could organize them into a book. I just had to be willing to sacrifice the time, which could have been spent developing actual sites, which instead had to go into writing lessons for other people.

It was a tough choice, but I chose to write the book, it seemed like a worthwhile endeavor. It turned out to be an incredible challenge. It pushed me mentally and physically. I spent long nights picking apart every detail, striving for excellence and clarity, so that others could more easily understand how to use Yii 2.

I started out fairly objective about PHP frameworks, simply looking for the easiest framework that could support robust development. Although I had a lot of respect for Symfony, I felt it was overly complicated and bloated. I didn’t like having to learn Yaml, even though it’s not difficult. I didn’t like having to write every route through the site. I didn’t like what I saw of doctrine. And I didn’t like the fact that alhough they had beautifully written documentation, there was no real effort made to service beginning programmers. This has a downside for businesses that have to hire programmers because it then becomes more expensive to train programmers. So in that sense, Symfony is an expensive discipline.

Laravel, on the other hand, went out of it’s way to service beginners and I loved that about it. The problem was, I just never felt like they were helping me build anything. None of the examples I found at the time, for example, dealt with a robust user login and verification. And without that, what kind of site do you have? And then, because it’s built on top of Symfony, it brings in Symfony’s bloat and performance issues. The other programmers at my company didn’t like it either. It didn’t seem robust enough to them, though in fairness, I should say that it was very new when we were doing those comparisons.

I turned to Yii 1.1.14 because my company had settled on it and the programmers loved it, but I found it difficult to grasp personally. In retrospect now, since I came up to speed on Yii 2, I understand 1.1.14 a lot better, but at the time, it seemed so difficult to use. The reality was that it was difficult to learn, but easy to use. You just had to be at a certain level as a programmer to get that. I hated that about it.

Then I discovered Yii 2 and everything changed. Whereaas Yii 1.1.14 was old and ugly, using old array syntax, no namespaces, etc., Yii 2 was a beacon of modern PHP. And being beautiful architecturally in this case is not just a superficial thing, it is extremely versatile and useful, way more intuitive than it’s predecessor. I have so much enthusiasm and passion for it, that I want to share it, and this was one of the motivations to write Yii 2 For Beginners.

Also, I know that right now, a beginning programmer is wandering around, wondering how to go from novice PHP programmer to framework developer. That’s a tough transition to make. I know just how frustrating it is. I want to help.

There are many, many, more advanced, and more qualified programmers than me, who apparently don’t have time or the interest to bring it down to the beginning level, so that task has fallen to me, at least in the short-term. I didn’t plan for this to happen, I’ve just found myself in these circumstances. There is no other beginning Yii 2 book out right now. So I did the best I could and I put a lot of effort into making Yii 2 as understandable for a beginning programmer as possible.

I realize that by being so into Yii 2, I no longer have objectivity to the other frameworks. That was bound to happen. I had to pick one. And when I get into something, I go all in.

So Yii 2 For Beginners is out now. I’m really glad I could contribute something to help beginners harness the potential of Yii 2, it really is an amazing framework.

Now that the book is done, I’m looking forward to getting back to application development, I hope to have a new site done in January. After that, I’m going on vacation, if I’m still breathing…

I will continue to support PHP and Yii 2 beginners on this blog, and hopefully continue with the polls, which people seem to find interesting. Over 1000 developers have voted in my polls. I hope to continue to develop this blog as a resource for the community.