All Tutorials

Your One-Stop Destination for Learning and Growth

Getting Started with Yii2: Controllers in Web Application Development (Part 2)

In the first part of this series, we covered the basics of setting up a new project using the Yii2 Framework. Now that we have a basic understanding of models and views, it's time to explore controllers and how they help us manage user requests and interact with our application.

Controllers: The Brain of Our Application

Controllers are PHP classes that handle incoming requests from users and return responses. They act as the middleman between the frontend (view) and backend (model). In Yii2, a controller is defined in a file within the controllers directory of our application.

Creating a New Controller

To create a new controller, let's follow these steps:

  1. Navigate to your project's controllers directory using your terminal or command prompt.
  2. Run the following command to generate a new controller called site:
    php yii generate controller site
    
  3. Open the newly created file located at controllers/SiteController.php.

Defining Actions in Controllers

Actions are methods defined within controllers that handle specific user requests. Each action returns a response, which can be a view, data, or redirect. Let's create an action called index:

  1. Inside the SiteController class, add the following code snippet for the index action:

    public function actionIndex()
    {
        return $this->render('index');
    }
    
  2. Create a new file named index.php within the views/site directory, which will be rendered when this action is called. For now, it can just be an empty file.

  3. Save both files and run your application by visiting http://localhost/your-project-name/ in your web browser. You should see an error since we haven't defined a route for our new controller action yet.

Defining Routes for Controller Actions

Routes map URLs to specific controller actions. To define a route, open the config/routes.php file and add the following code:

'urlManager' => [
    'rules' => [
        '/' => 'site/index', // This is our home page route
    ],
],

Save the file and restart your application. Now when you visit http://localhost/your-project-name/, you should see an empty "Welcome to Yii2" message displayed as the result of our actionIndex() method in the SiteController.

In the next part of this series, we'll dive deeper into controllers and explore more advanced topics like passing data between views and models, custom error pages, and more. Stay tuned!

Published July, 2017