How do you create custom controllers in Yii?

How do you create custom controllers in Yii?

Here are the minimal steps to create a custom controller in Yii:

1. Create the Controller

Create a new PHP file in the controllers directory. The class should extend yii\web\Controller.

Example

<?php
namespace app\controllers;

use yii\web\Controller;

class ProductController extends Controller
{
    public function actionIndex()
    {
        return 'This is the product index page.';
    }

    public function actionView($id)
    {
        return "Viewing product with ID: $id";
    }
}
?>

2. Create Views (Optional)

If you want to render views instead of returning plain text, create a folder product inside the views directory and add view files.

  • views/product/index.php:

Example

<?php
<h1>Product List</h1>
?>

views/product/view.php:

Example

<?php
<h1>Viewing Product <?= $id ?></h1>
?>

Update your actions to render these views:

Example

<?php
public function actionIndex()
{
    return $this->render('index');
}

public function actionView($id)
{
    return $this->render('view', ['id' => $id]);
}
?>

3. Access the Controller

Access your controller actions via the browser:
  • /product/index or /product: Displays the product index.
  • /product/view?id=1: Displays product details for ID 1.
That’s it! These are the steps to create and access a custom controller in Yii.

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.