create custom controller in codeigniter 4

Deepak Tailor Image
Deepak Tailor - Sep 23 2020
create custom controller in codeigniter 4

A Controller is simply a class file that is named in a way that it can be associated with a URI. First uri segment is controller name

url example :

domain.com/index.php/helloworld/

Save the controller file in the App/controllers/controller_file_name folder.

This is valid:

class Helloworld extends Controller
{

}

This is not valid

class helloworld extends Controller
{

}
class HelloWorld extends Controller
{

}

Also, always make sure your controller extends the parent controller class so that it can inherit all its methods.

Passing URI Segments to your methods
domain.com/index.php/products/mobile/sansung/123
public function mobile($name, $id)
{
    echo $name;
    echo $id;
}
Defined a default controller

You can also set the default controller in the coding controller when the product is run, then the default controller is run.

To specify a default controller open your app/Config/Routes.php file and set this variable:

$routes->setDefaultController('Helloworld');
Defined a route for controller
$routes->get('/', 'Home::index');
$routes->get('/aboutus', 'Home::about_us');
$routes->get('/products', 'Home::products');
$routes->get('/services', 'Home::services');
$routes->get('/contactus', 'Home::contact_us');

You cannot call protected and private function from direct URL. Codeigniter 4 controller, how to create controller, call function in controller

Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry for the last 5 years. For professional and customize web development, you can send inquiry on our email.
----
You can contact him at support@fulstackdev.com