Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Creating a base controller | Controllers
PHP MVC Development

bookCreating a base controller

メニューを表示するにはスワイプしてください

Note
Definition

A base controller is a reusable PHP class that provides shared logic, methods, or properties for all other controllers in an MVC application.

In an MVC application, many controllers perform the same tasks, such as rendering views, validating input, and setting headers. Instead of repeating this code in every controller, you can move the shared logic into a base controller class.

This approach reduces duplication, simplifies maintenance, and keeps behavior consistent across the application.

BaseController.php

BaseController.php

copy
12345678910
<?php class BaseController { public function render($view, $data = []) { extract($data); include __DIR__ . "/views/{$view}.php"; } }

By defining common functionality like the render method in the BaseController, you allow other controllers to inherit these features. Child controllers can extend the base controller, gaining access to its methods and properties without having to redefine them.

HomeController.php

HomeController.php

views/home.php

views/home.php

copy
123456789101112
<?php require_once 'BaseController.php'; class HomeController extends BaseController { public function index() { $data = ['message' => 'Welcome to the home page!']; $this->render('home', $data); } }

Using inheritance in your controller design means that any improvements or bug fixes to shared logic in the base controller are instantly available to all child controllers. This makes your codebase easier to maintain and extend, especially as your application grows.

question mark

Why create a base controller class in MVC?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt