How to create a controller in Yii?

Member

by orpha , in category: PHP Frameworks , a year ago

How to create a controller in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a year ago

@orpha 

Yii is a high-performance, component-based PHP web application framework that allows you to create modern and scalable web applications. To create a controller in Yii, you can follow the steps below:

  1. Create a new PHP file in the controllers directory of your Yii application. The file name should follow the convention MyController.php, where MyController is the name of your controller.
  2. In the new PHP file, define a new class with the same name as the file (in this case, MyController). The class should extend the yiiwebController class, which is the base class for all controllers in Yii.
1
2
3
4
5
6
7
8
namespace appcontrollers;

use yiiwebController;

class MyController extends Controller
{
    // controller actions will be defined here
}


  1. Define one or more actions in the controller class. An action is a public method that handles a specific user request. Actions in Yii are identified by their method names, which are prefixed with the word action. For example, if you want to create an action that handles requests to the URL /my/action, you can define a method named actionIndex:
1
2
3
4
public function actionIndex()
{
    return $this->render('index');
}


  1. Inside the action method, you can use the $this->render() method to render a view file that will be displayed to the user. In the example above, the method returns the output of the index view file.
1
2
3
4
public function actionIndex()
{
    return $this->render('index');
}


  1. You can also define action parameters to handle dynamic parts of the URL. For example, if you want to handle requests to /my/action/123, you can define a parameter named $id:
1
2
3
4
5
public function actionView($id)
{
    $model = MyModel::findOne($id);
    return $this->render('view', ['model' => $model]);
}


  1. Finally, you need to configure the routing to map requests to the correct controller and action. You can do this by modifying the urlManager component in your application configuration file (config/web.php). For example, to map requests to /my/action to the MyController class and the actionIndex method, you can add the following rule:
1
2
3
4
5
6
7
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        'my/action' => 'my/index',
    ],
],


In this example, the my/index route will map to the MyController class and the actionIndex method.


That's it! With these steps, you can create a basic controller in Yii and handle user requests. You can learn more about Yii controllers and actions in the official documentation: https://www.yiiframework.com/doc/guide/2.0/en/structure-controllers