Welcome back to our beginner’s journey in Yii 2. I’ve made it my mission to help programmers at the beginning stages of framework development to learn about Yii 2, one of the most intuitive and powerful PHP frameworks available.
For those just getting started, I recommend my book, Yii 2 For Beginners, which will take you step by step through setup and onto coding. The book focuses on learning Yii 2 and building a reusable template that can serve as a starting point for your projects. It shows you how to do things, but also explains why we do things the way we do.
This blog serves as an extension of the book, where I share development tips and tutorials that will help you learn more about Yii 2. I also roll out new pieces of the template, which will be incorporated into the book on a quarterly basis. Anyone who purchases the book, gets free updates for the life of the book, so please take advantage of that, if you can.
Today’s tutorial is about implementing a simple test controller to help you with development. This tutorial is for beginning level programmers.
Sometimes in development, you want to isolate a block of code and play with it, without cluttering up your other code. Now version control should always be there if you made a huge mistake, but you really don’t want to be relying on that to step backwards unless you absolutely have to.
So what we’ll do is create a controller named test. We start by navigating to Gii, and clicking on Controller Generator. We don’t have to worry about creating a model first, since we don’t have one, our test controller will be used to play around with different bits of many models, and we will pull in the models via use statements as we need them.
If you don’t know how to use Gii or haven’t started using the framework yet, I would recommend learning that first before moving on to this tutorial. We’re assuming here that you know how to use Gii, which is Yii 2’s built-in code generator.
Ok, so back to the create Controller form on Gii. Pop in test into the first input field to name the controller. We will create just one action for now, Index. Then check to see if the namespace is set to where you want it to go.
In the advanced template, which is what I use because they provide a working user model, I’ve created a test controller for both frontend and backend, though that’s not really necessary. It just helps me when I’m thinking of things to intuitively associate a backend test controller with things I want to try in the backend. Also, sometimes, I leave code in place in the test controller while I’m thinking about whether or not I want to use it.
Ok, so when you hit preview on Gii, it will show two files, the controller and the view file. Once we click generate, it will also create the directory to hold the view file. So let’s do that now.
If all went well, you should have a TestController.php file in frontend\controllers and a frontend\views\test\index.php file.