Understanding Controllers in CodeIgniter

Aug 22, 2024

Controllers in CodeIgniter

Overview

  • Tutorial by Alex from Alex Lansford.
  • Focus on understanding controllers in CodeIgniter.

Definition of Controllers

  • A controller is a class file associated with a URI (Uniform Resource Identifier).
  • Example: In a home controller (home.php), accessed via localhost/home.
  • Default controller is loaded when no specific URL is provided.

Creating a New Controller

  1. Duplicate home.php: Rename to shop.php and change class name to Shop.
  2. Naming Convention: First letter uppercase, rest lowercase.
  3. Update View: Change view from welcome page to shop.
  4. Create View File: views/shop.php with content <h2>This is a shop</h2>.

Accessing the Controller

  • Navigate to localhost/shop to see the shop page.

Methods in Controllers

  • Each controller can contain methods that can be accessed via the URI.
  • Example: Create method product in Shop controller:
    • Access: localhost/shop/product
    • Create view file product.php with content <h2>This is a product</h2>.

Dynamic Product Access

  • Allow dynamic access to products via URI parameters:
    • Change method to accept parameters and echo them:
      echo '<h2>This is a product ' . $type . '</h2>';
      
  • Example: Access localhost/shop/product/laptop shows "This is a product laptop".

Protected Methods

  • Use protected for methods that shouldn't be publicly accessible:
    • Example: protected function admin() will give a 404 error when accessed directly.

Organizing Controllers

  1. Create Admin Folder: Inside controllers, create admin folder.
  2. Duplicate Shop: Copy shop.php into admin folder, rename as Shop.php.
  3. Update Namespace: Ensure the namespace reflects the folder structure:
    • Use statement for base controller must reflect its location.

Testing Admin Controller

  • Access localhost/admin/shop to check if it works.
  • Change content to indicate it's the admin area:
    • Example output: <h2>This is an admin shop area</h2>.

Using Namespaces

  • Allow use of controllers in different namespaces without conflicts:
    • Example: Use both Shop and Admin\\Shop in the same controller.
  • Add Use Statements: Handle namespaces to avoid class name conflicts:
    use App\Controllers\Admin\Shop;
    

Practical Example

  • Create instances of both shop classes in the Home controller:
    • Handle them using different names to avoid conflicts:
    $shop = new Shop();
    $adminShop = new AdminShop();
    

Conclusion

  • Understanding of controllers, methods, and namespaces is crucial for CodeIgniter development.
  • Next tutorial will cover routing and creating dynamic URLs.