CI 4 What is Controller?

Share this Article

Controllers are the classes files in CodeIgniter 4. By the help of these classes we can control the flow of application.

It connects the user view means layout with models. It takes data from database by the help of models and inject it to the user views.

Controllers are stored inside /app/Controllers folder.

Inside /app/Controllers folder, you will see – Home.php & BaseController.php

By default when you install CodeIgniter 4 setup. Home.php is a default controller created by setup whereas BaseController.php is the parent controller in application. If we want to define anything at application level say – loading any helper, we can do by this file.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function index()
	{
		return view('welcome_message');
	}
}

App\Controllers is the namespace where controller is.

How to Create Controllers?

Controllers will be by using spark CLI command. Here is the syntax –

$ php spark make:controller <ControllerName> --suffix

<ControllerName> It’s a user defined name. –suffix is optional. If we add, then class file name has file suffix of Controller.

Example

$ php spark make:controller Site

It will create Site.php inside /app/Controllers folder.

$ php spark make:controller Site --suffix

It will create SiteController.php inside /app/Controllers folder.

There is no specific naming convention for Controllers in CodeIgniter 4, you can choose with suffix or without suffix both will work.

Learn Web Development Courses @ $4 only.
Web Development Courses @ $4